Reputation: 10297
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?
Upvotes: 1
Views: 13856
Reputation: 5953
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
Upvotes: 16
Reputation: 708156
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.
Upvotes: 5