简体   繁体   中英

take out option from javascript

how to take out option value = 0 using javascript from below

<select>
<option value=0>0</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>

Thanks

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM