简体   繁体   中英

Why does javascript not see the “selected” attribute on my select option?

Short version:

After inserting a select element with options into the DOM with an AJAX call the "selected" attribute on my option isn't recognized by the JavaScript. It's as if it's not there even though looking at it in Firebug I can see that it is.

Long version:

I'm using a jQuery plugin that generates a "multi select" (select imitation with checkboxes pretty much) based on an actual html select with options that can have a "selected" attribute. The plugin checks if the selected attribute exists by doing

$(this).attr('selected') == true

and if it exists it sets the corresponding checkbox to checked. This all works when I load the page normally. I also need to reload the data if the user chooses to filter it and here is where the problem is. The new data is fetched via AJAX and the plugin is reapplied to new markup but the "selected" attribute isn't considered present even though it's there just like before . Other attributes work fine but "selected" bizarrely enough doesn't. This is the markup both when it works and when it doesn't.

<option value="1" selected="selected" warning="true"> text</option>

I'm really scratching my head over this. Anyone got a suggestion?

Forget jQuery's confusingly named attr() method and attributes in general, and instead just use the selected property of the option, which is a Boolean and works in all major browsers released since 1996:

// Assuming the select list is stored in a variable called select
alert( select.options[0].selected );

If you must use jQuery to get the option, here's the equivalent:

alert( $(this)[0].selected );

Attributes are almost never what you want, since they are incorrectly implemented in IE and only ever represent the initial value of a some aspect of the element, not the current value. jQuery's attr() method generally uses properties internally.

why are you comparing to true ? the "selected" value is "selected" , not true .

您获得的元素在其中Selected == True但已选定的地方实际上是“已选定”。

A better way to check if an option is selected, type the following:

if ($(this).is(":selected")) {
 ...
}

So, if you want to detect all selected options you could use:

$("select option:selected").each(function () { ... });

Perhaps, this fixes the problem.

I figured out what the problem was. We use a js combiner and apparently moving the include call to a different file fixed the problem.

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