开发者

How to retrieve empty OPTION value if it's empty?

Considering we have this HTML:

<select id="my_select">
  <option value="1">Foo</option>开发者_开发技巧;
  <option value="2">Bar</option>
  <option value="">Bork</option>
  <option value="3">Hey!</option>
</select>

The proper way to get the chosen value would be:

var oS = document.getElementById("my_select");
alert(oS.options[oS.selectedIndex].value);

But if the third option, Bork, is chosen, the alert() will show "Bork" and not "" (empty string).

How do I retrieve the empty string?


Firstly, it doesn't. For me, in Chrome and IE8, your example alerts an empty string (jsFiddle).

If, however, there is no value set at all (jsFiddle), Bork is alerted. This is, I think, the issue you're coming up against. This is correct behaviour. As the MDC page says,

If it is not defined, its default value is the text content of the element.

You could, however, use the getAttribute method, which gives null if no elements are selected (jsFiddle).

var oS = document.getElementById("my_select");
alert(oS.options[oS.selectedIndex].getAttribute('value'));


alert(document.getElementById("my_select").value)

returns the empty string, or any defined value of the selected option.

no need to specify options[selectedIndex]

If there is no default selected index, the first option value is returned.

If there is no value attribute for the selected option,

the option's text is returned in a script alert in most browsers,

and is sent to the server (if the select has a name and a form action) in all browsers.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜