Jquery - Why do we write .attr ('selected', 'selected') with a select tag

why write .attr('selected','selected') with select tag

For ex:

 $('#countryList option').filter(function () { return ($(this).text() == findText); }).attr('selected','selected'); }); 

What does it mean?

+4
source share
7 answers

Explanation of .attr('selected','selected') .

The first argument inside .attr represents the attribute you want to point to, and the second argument is the set value attribute that is passed as the first argument.

if we only have .attr('selected') then it just returns the value of the selected attribute.

+2
source

why we write .attr ('selected', 'selected')

Since jQuery is allowed to select, if you want to set the selected select item, you can use val () to set the selected option

 $('#countryList').val(5); // it will set the selected attribute for option having value 5 
0
source

.attr() The jquery method is used to set selector attributes. Thus, in your case, this function is used to show the text as selected in the drop-down list.

See the tutorial here .

0
source

In general, the selected attribute is respected by most browsers for its simple presence / absence, regardless of its value. According to the specification, this is a logical attribute (when installed via javascript), but in HTML markup this attribute is usually represented by its presence / absence. This means that by default the item is displayed in the drop-down list.

0
source

See what happens:

 $('#countryList option').filter(function () { return ($(this).text() == findText); }).attr('selected','selected'); }); //<---------this is extra 

Ok, but the question is why we write .attr('selected','selected') with the select tag :

If you see that you are not setting the selected attribute to <select> , but <option> , it contains.

Your code will set the selected attribute to option , which contains the text equivalent to findText

0
source

selected is the boolean property of <option> ; expressed in HTML attributes, its value is either empty (or not specified), or equal to the attribute name itself, indicating true (by convention).

 $('#countryList option').filter(function () { return ($(this).text() == findText); }).attr('selected','selected'); 

This code sets the selected attribute for the first element of the match option. In fact, the code has several problems:

  • The .attr() function is called regardless of the filtering results.
  • The selected attribute is not strictly an attribute, but a property.

It could be rewritten as follows:

 $('#countryList option').each(function () { if (this.text == findText) { this.selected = true; return false; // stop searching after we find the first match } }); 
0
source

In any programming language, when you want to set a property, you need to assign a value related to this property. So jquery does the same.

0
source

All Articles