最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览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?

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>

发布评论

评论列表(0)

  1. 暂无评论