简体   繁体   English

多个选择框使用 jquery 确认至少选择了一个选项

[英]multiple select box use jquery to confirm atleast one option selected

I have a select box that I need to check with jquery on mouseleave if there's an option selected however suggestions like $('#category').attr("selectedIndex") returns undefined even when an option has been selected.我有一个选择框,如果选择了一个选项,我需要在 mouseleave 上使用 jquery 检查,但是即使选择了一个选项,诸如$('#category').attr("selectedIndex")建议也会返回 undefined 。

HTML below:下面的 HTML:

<select id="category" multiple="multiple" class="category">
    {% for category in categories %}
       <option value="{{ category.id }}">{{ category.name }}</option>
    {% endfor %}
</select>

I have Django dump a list of options so for the above options list.我让 Django 转储了一个选项列表,所以对于上面的选项列表。 I'd prefer if the code can filter by select id category so for it doesn't intefer with any other select boxes.我更喜欢代码是否可以按选择 id category进行过滤,因为它不会干扰任何其他选择框。

You can try你可以试试

$("#category option:selected").index()

or

$("#category").prop("selectedIndex")

I think .prop is for the newer versions of jquery.我认为 .prop 适用于较新版本的 jquery。

$("#category").on('focusout',function() {
  console.log($(this).val());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM