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?
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?
Share Improve this question edited Apr 28, 2016 at 22:44 The Process 5,9533 gold badges32 silver badges41 bronze badges asked Apr 26, 2016 at 21:31 B. Clay Shannon-B. Crow RavenB. Clay Shannon-B. Crow Raven 10.2k157 gold badges498 silver badges896 bronze badges 6 | Show 1 more comment2 Answers
Reset to default 16 +50The .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
Because $("#delperfto")
is NOT a DOM element. It's a jQuery object and a jQuery object does not have a .selectedIndex
property. A jQuery object is its own type of object with its own properties and methods. It does not have the same properties and methods as a DOM element. It often has a way of accomplishing the same thing, but usually with different syntax.
You can either fetch a DOM element from the jQuery object and access that DOM element directly like this:
$("#delperfto")[0].selectedIndex = -1;
or
$("#delperfto").get(0).selectedIndex = -1;
Or, you can use jQuery's .prop()
method to have it set the desired property on each DOM element for you like this:
$("#delperfto").prop("selectedIndex", -1);
There's no particular advantage to one or the other in this specific circumstance, but if your selector returned more than one element in it such as this:
$(".options").prop("selectedIndex", -1);
then the jQuery .prop()
method would set that property on all DOM elements that the selector matched, not just the first one which can sometimes be quite useful.
selectedIndex
. – Felix Kling Commented Apr 26, 2016 at 21:35$("#delperfto")[0].selectedIndex = -1;
? – Alon Eitan Commented Apr 26, 2016 at 21:36