简体   繁体   中英

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.

HTML below:

<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. I'd prefer if the code can filter by select id category so for it doesn't intefer with any other select boxes.

You can try

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

or

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

I think .prop is for the newer versions of jquery.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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