开发者

Behavior of val() for multiple select in jQuery changed?

So everywhere I looked开发者_如何学运维 everybody says that to output values of selected options in a multiple select element one should use something like the following $('#selid :selected').val() and that in such case val() will return an array of values. Well, I can't replicate this behaviour. As far as I can tell such code returns just the first selected value. Here's a quick jsfiddle snippet that demonstrates that.

Notice that using each to iterate through $('#selid :selected') does work, but calling val() on that array does not produce an array of values as far as I can tell. In fact, calling $('#selid :selected').val().each(... results in an error message.

So, am I doing something wrong or has this behavior been changed at some point?


"in such case val() will return an array of values. Well, I can't replicate this behaviour."

You never need to use :selected to get the value of a <select>. This is sufficient:

$('#selid').val()

Demo: http://jsfiddle.net/mattball/WZRmD/


The val function gets the value of the first element in the set of matched elements. To get the value of multiple selected items, when using the :selected selector, you need to loop through the set, as you mention in your question.

For more information, read the jQuery API for val().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜