jQuery 1.6, changed its .val() behavior?
In jQuery 1.6, it seems to me that the .val()
function has been changed since jQuery 1.5.2.
When I call it on a select's option to get a value, now I get the text. For example:
<option value="1">john</option>
When I call:
$('select').val();
with jQuery 1.5.2 I get 1 while with jQuery 1.6 I get john
I know they changed behavior of .attr()
and introduced .prop()
, but at this link I'm not ab开发者_运维技巧le to find anything about .val()
.
Here is an example that shows this difference and what I've tried so far to get the option's value. Switch from jQuery 1.6 to jQuery 1.5.2 to see.
How do I get an option's value with jQuery 1.6?
Your mistake in your jsfiddle example is to use val
to create the value, for this you should rather use attr('value', id)
. Then val()
still works as expected, the same as in previous versions, and you can get the option
value with it.
http://jsfiddle.net/KFDWm/5/
There was a bug in v1.6 where val('asdf')
no longer sets the value: http://bugs.jquery.com/ticket/9071 This bug has been fixed in v1.6.1.
Also, despite what others have said, it's totally okay to use val() to set the value---actually, according to the jQuery team it's preferred over using attr('value', 'asdf')
.
精彩评论