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?
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?
Share Improve this question edited Aug 5, 2019 at 11:30 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 4, 2019 at 3:39 RunRun 57.4k178 gold badges464 silver badges771 bronze badges 1- Possible duplicate of Get selected value in dropdown list using JavaScript – Claire Commented Aug 4, 2019 at 3:48
2 Answers
Reset to default 4Because 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>
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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745502278a4630471.html
评论列表(0条)