1 year ago

#133997

test-img

MHSchultz

How can I replace a CLICK in a <select> dropdown list with a CTRL+CLICK in Javascript?

A client wants a multi-select dropdown list that replaces the normal mouse click behavior with a CTRL+CLICK, as though the CTRL key is pressed while clicking the mouse. The client was warned that this changes expected behavior and wants it anyway. Initially I want to replace the default click behavior with the CTRL+CLICK behavior. I want to use the select element and not something else as some posts suggest.

My idea was to stop the click and replace it with a simulated CTRL+CLICK. I added the onmousedown attribute to the select statement. The JS disables the default click behavior and then I've tried to create and dispatch the same mouse click event with ctrlKey set to true...but nothing happens. Nothing is selected or deselected like the default CTRL+CLICK behavior should.

I'm new to JavaScript event handling, so I'm sure I'm missing something. Can someone help?

<select id="selectbox" multiple onmousedown="SelectDeselect(event)">
  <option id="option1">A</option>
  <option id="option2">B</option>
  <option id="option3">C</option>
</select>

<script>
function SelectDeselect(event) {
    event.preventDefault();
    optn = event.target;
    var ctrlClickEvent  = new MouseEvent("click", {
        ctrlKey: true,
    })
    document.getElementById(optn.id).dispatchEvent(ctrlClickEvent);
}
</script>

javascript

select

mouseevent

ctrl

onmousedown

0 Answers

Your Answer

Accepted video resources