michaelmcgurk
michaelmcgurk

Reputation: 6509

Select item from multiple select menu

This is a strange bug I have in my script.

When I click the option "Test", the alert appears.

However when I select it (using the control key) it doesn't alert.

As a test, ctrl select 'Desktop' then click 'Test'. You'll see no Alert :(

Why is this?

JS:

var $cb = document.querySelector("#equipments");

$cb.addEventListener("change", function() {
    if ($cb.value == "test") {
        // if true 
        alert("Selected!");
    } else {
        // false 
    }
})

HTML

<select id="equipments" name="equipments[]" multiple="multiple" class="form-control" multiple data-live-search="true" required>
  <option value="laptop">Laptop</option>
  <option value="desktop">Desktop</option>
  <option value="test" >Test</option>
  <option value="none">None</option>
</select>

Fiddle: https://jsfiddle.net/0mvngqsc/

Upvotes: 0

Views: 36

Answers (2)

UmairFarooq
UmairFarooq

Reputation: 1315

there is a property called selectedOptions which gives us the object of the selected items.i am just iterating through that object using for of.unfortunately couldn't get it working on change event.i hope this helps you to reach your results

    var $cb = document.querySelector("#equipments").selectedOptions;
    var $sb = document.querySelector("#submit");


    $sb.addEventListener("click", function () {
        for (let el in $cb) {
            console.log($cb[el].value);
            if ($cb[el].value == "test") {
                // if true 
                alert("Selected!");
            }
            else {

                // false 
            }


        }


    })
<select id="equipments" name="equipments[]" multiple="multiple" class="form-control" multiple
        data-live-search="true" required>
        <option value="laptop">Laptop</option>
        <option value="desktop">Desktop</option>
        <option value="test">Test</option>
        <option value="none">None</option>
    </select>
    <button id="submit">Submit</button>

Upvotes: 1

Adnan Malik
Adnan Malik

Reputation: 81

You cannot. The change event does not define ctrlKey, as you have noted. change is an event which uses the base event interface, which does not handle ctrlKey. To have ctrlKey defined, you need to use a TouchEvent, MouseEvent, or KeyboardEvent.

Upvotes: 1

Related Questions