html - Vanilla JavaScript - How to check a option is selected in multiple select options? - Stack Overflow

To check whether a checkbox is ticked we do this:let isChecked = event.target.checkedWhat about a multi

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
Add a ment  | 

2 Answers 2

Reset to default 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>

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信