Set selected option by value via jQuery

This article describes how to set the selected option in a select by its value via jQuery.

commit 721229e · authored · 1 min read

Set selected option by value via jQuery

In one of my projects, there is a search page which has few filters including linked selects, i.e the options displayed in a child select is dependent upon the option selected in another (parent). (like when we choose a country (parent), we have to show the states under the selected country in the child.)

After selecting both select, when we submit the search, it loads search result page with same filters above. The problem is that the child select value is not retained. Since when we assign the parent select selected value, it will trigger an ajax call and its response is bound to the child select.

To retain the filters as users selected, we had to set the selected value in the child select also. My child select is (Razor)

@Html.DropDownList("childSelectName", items, new { @name = "someName" })

And inside my ajax call on parent select on change, after binding all the available option to the child select,

if (selectedChildItemId) {
$("#childSelectName").val(selectedChildItemId);
}

In short,

$("#Controls_ID").val(value);

Replace the Controls_ID with your select tag Id and value with the selected item value.

local graph · open full graph

"Set selected option by value via jQuery" is connected to the topics JavaScript, jQuery and related to 6 other entries. Remove specific class from all elements - jQuery Remove specific class from … Get/Set hidden field value using jQuery Get/Set hidden field value … Vue.js List Rendering : Limit items in v-for Vue.js List Rendering : Lim… JavaScript - Determine if user is on mobile device JavaScript - Determine if u… Decode JWT Token Decode JWT Token Domain Name From URL Domain Name From URL JavaScript #javascript jQuery #jquery Set selected option by value via …

comments

loading discussion…