I have a complex form with lots of elements.. In a way, all kinds of element!! User select values from drop down (ComboBox) that are dynamically loaded using Ajax. Upon selecting a value, the next drop down or form element values change or are set. I require to set default values to these dropdowns. Lets take a simple drop down:
<select id="centerTypeDropDown" name="centerType">
<option value="ASC" selected="selected">ASC</option>
<option value="NSC">NSC</option>
<option value="USC">USC</option>
<option value="IKT">IKT</option>
<option value="UCC">UCC</option>
</select>
The default selected value is ASC. In my application, these values are loaded using Ajax and the default values may change when user select other form elements or drop down. So, in short, new elements get added into this drop down and the selected value changes. For our example, let's say we need to set the default selection to USC instead of ASC.Using jQuery I can change the default selection to the required option. Here is how to do it:
$("select#centerTypeDropDown option[selected]"). removeAttr("selected"); $("select#centerTypeDropDown option[value='USC']"). attr("selected", "selected");That's it! For jQuery beginners, selector string is the magic string. selector returns a object or collection of objects. Using selectors, I can select any DOM object and then use appropriate methods to manipulate its properties. In this case, I need to change the selected attribute to another option. The first line for code is used to select the current selected value in the drop down and then by using the removeAttr method, I remove the attribute from the option tag. The second line of code is used to set the new selected value. I select the same object again then use attr method to set the appropriate attribute.
The above code works fine when we know exactly what our new default value is. What if we get the values and default value from the server dynamically? For example my JSON returned from the server contains new or additional options and default value. Note that, in above code we specify which option to be selected in the sector string through option[value='USC']. In our case, we cannot hard code the selector string, instead we create it dynamically.
var selectorSrting = "select#centerTypeDropDown option[value='"+ defaultValueObtainedFromServer + "']"; $(selectorSrting).attr("selected","selected");And that's our final code! Let me know if there are better solutions to this problem. And intersted readers, watch out for the next article on dynamically loading ComboBox using jQuery.