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" 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/
CodePudding user response:
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.
CodePudding user response:
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" 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>