0

To check whether a checkbox is ticked we do this:

let isChecked = event.target.checked

What about a multiple select options like this below?

<select name="books[]" multiple>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

How can we check if A is selected or when A is unselected when you select B?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Run
  • 54,938
  • 169
  • 450
  • 748
  • Possible duplicate of [Get selected value in dropdown list using JavaScript](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – Claire Aug 04 '19 at 03:48

2 Answers2

4

Because of the way multiple-selection elements work with values, simply check the new value. If it's A, then the first selected element is A.

document.getElementById("books").addEventListener("change", function(e) {
  console.log(this.value == "A");
});
<select name="books[]" id="books" multiple>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
2

You can check the length of selected option:

document.querySelector('select').addEventListener('change', function(){
  console.clear();
  let sel = this;
  let checked = [...sel.options].filter(option => option.selected).map(o => o.value);
  let isA = checked.includes('A') ? 'A selected' : 'A not selected';
  let isChecked = checked.length > 0 ? 'Selected' : 'None selected';
  console.log(isA);
  console.log(isChecked);
});
<select name="books[]" multiple>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>
Mamun
  • 66,969
  • 9
  • 47
  • 59