views:

12363

answers:

4

How do I set the index of a dropdown in jQuery if the way I'm finding the control is as follows:

$("*[id$='" + originalId + "']")

I do it this way because I'm creating controls dynamically and since the ids are changed when using Web Forms, I found this as a work around to find me some controls. But once I have the jQuery object, I do not know how to set the selected index to 0 (zero).

Thanks in advance for the help!

A: 
$("[id$='" + originalId + "']").val("0 index value");

will set it to 0

jmein
+12  A: 

First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element.

$(".myselect")

To answer your question though, there are a few ways to change the select elements value in jQuery

// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0'); 

// sets selected index of a select box to the option with the value ""
$("select#elem").val(''); 

// sets selected index to first item using the DOM
$("select#elem").get(0).selectedIndex = 0;
gnarf
is there a better way to do it? I figured it'd scan the whole DOM looking to match the ID, but since I'm new to jQuery I figured, let's make it work and then see if there's a better way to do it. Any advise will be appreciated.
oz
Yes - if you can assign a class to the element(s) you need to find, it would be a much faster selector.
gnarf
A: 

You want to grab the value of the first option in the select element.

$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));
MacAnthony
+1  A: 

Just found this, it works for me and I personally find it easier to read.

This will set the actual index just like gnarf's answer number 3 option.

// sets selected index of a select box the actual index of 0 
$("select#elem").attr('selectedIndex', 0);

This didn't used to work but does now... see bug: http://dev.jquery.com/ticket/1474

Kohan