开发者

Take out option from JavaScript

How to take out option value = 0 using JavaScript from below:

<select>
<option value=0>0</option>
<option va开发者_JAVA百科lue=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>


var select = document.getElementsByTagName("select")[0];
for (var i  = 0; i < select.options.length; i++) {
    if (select.options[i].value === "0") {
        select.remove(i);
    }
}

See a live example. Annoyingly the value is a string so you have to === compare to the string. And getting the select by tagName assuming it's the only select on the page is prone to failure

using

<select id="foo"> ... </select>

and

var select = document.getElementById("foo");

Would be better.


If you can use jQuery:

$('select > option[value=0]').remove();

Obviously you should use the id of the select instead of select or you will hit all select items on that page.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜