开发者

jQuery getting value from a drop down selected

traditionally we write

var value = $("#drop-down-id").val();开发者_开发知识库

to get the value. IN my case, some of the options contains multiple words with spaces like "Allow All","Internet Users" etc. What I am getting in VALUE is only "Allow" that is, jquery is trimming off words after the white space. Is there any other way to solve this?


If you have the value wrapped in the <option></option> and you don't use the val attribute directly, you can do:

var value = $('#drop-down-id option:selected').text();


try with:

var value = $("#drop-down-id option:selected").attr("value");


This makes no sense. There should not be any need to get the option text. If you need to do so, then your option elements are likely populated the wrong way in the server side.

Check the HTML source, you're likely forgotten the quotes around the option's value attribute.

This one is wrong:

<option value=John Doe>John Doe</option>

It would only return the first word as the actually selected value, because the space is actually an attribute separator in HTML; now you'll get "John" as value and the "Doe" is seen as another (non-existing ) HTML attribute.

This one is correct

<option value="John Doe">John Doe</option>

This way you'll get "John Doe" as value.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜