B. Clay Shannon B. Clay Shannon - 2 years ago 373
Javascript Question

How to set .selectedIndex with jQuery

I have some html selects:

<select class="form-control, dropdown" id="delperffrom" name="delperffrom">
. . .
<select class="form-control, dropdown" id="delperfto" name="delperfto">
. . .

I want to initialize them to "no value" and so have this javascript, which works:

document.getElementById("delperffrom").selectedIndex = -1;

..and this jQuery, which doesn't:

$("#delperfto").selectedIndex = -1;

Why does the jQuery not work?

Answer Source

The .selectedindex is property of the DOM element, not jQuery.You can change it on DOM element, or using jQuery .prop() method:

$("#delperffrom")[0].selectedIndex = -1; // change on dom element pulled from jQuery
$("#delperffrom").prop('selectedIndex',-1); // change with .prop() jquery method
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download