Home  >  Article  >  Web Front-end  >  How to determine whether option is selected in jquery

How to determine whether option is selected in jquery

coldplay.xixi
coldplay.xixiOriginal
2020-12-07 17:01:135995browse

How jquery determines whether an option is selected: First, the option belongs to the select, and the value of the select can be obtained through jquery; then, by comparing each option under the select, you can determine whether it is selected.

How to determine whether option is selected in jquery

The operating environment of this tutorial: windows7 system, jquery3.2.1 version, Dell G3 computer. This method is suitable for all brands of computers.

Recommended: jquery video tutorial

jquery method to determine whether option is selected:

option belongs to select and can be passed through jquery Get the value of select; then compare each option under select to determine whether it is selected.

var selectValue = $('select').val();
$('select option').each(function(ele,index){
    if($(ele).attr('value') == selectValue){
        alert('被选中');
    }
});

Description:

1. val() method

val() method can return the value of the selected element Attribute; returns the value of the value attribute of the first matching element.

Note: The val() method is typically used with HTML form elements.

2. Each() method

each() method specifies the function to be run for each matching element.

Tip: Returning false can be used to stop the loop early.

3. attr() method

attr() method sets or returns the attributes and values ​​of the selected element.

When this method is used to return an attribute value, the value of the first matching element is returned.

When this method is used to set attribute values, one or more attribute/value pairs are set for the matching element.

Related free learning recommendations: javascript(Video)

The above is the detailed content of How to determine whether option is selected in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How jquery handles eventsNext article:How jquery handles events