18
Apr
Working with dropdown box in jQuery
Suppose we have the following drop-down list
1: <select id="box" > 2: <option value="1">Value 1</option> 3: <option value="2">Value 2</option> 4: <option value="3">Value 3</option> 5: <option value="4">Value 4</option> 6: <optgroup label="Group1"> 7: <option value="5">Value 5</option> 8: <option value="6">Value 6</option> 9: <option value="7">Value 7</option> 10: <option value="8">Value 8</option> 11: </optgroup> 12: </select>
Trick #1: to get the selected value
$("#box").val();
Trick #2: to get the text of the selected item
$("#box option:selected").text()
Trick #3: detect changes and do something with changes
$("#box").change(function() { /* do something here */ });
Trick #4: set the selected item
$("#box").val(2);
Credits go to Elegant Code
0 Comments