7

Set the selected index of a drop-down list using jQuery

 2 years ago
source link: https://www.codesd.com/item/set-the-selected-index-of-a-drop-down-list-using-jquery.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Set the selected index of a drop-down list using jQuery

advertisements

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).


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")[0].selectedIndex = 0;

// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);

Tags jquery

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK