Created
December 23, 2015 06:53
-
-
Save shameersn/919084c3de2358eb2415 to your computer and use it in GitHub Desktop.
JQuery setting the selected attribute on a select list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| If you don't mind modifying your HTML a little to include the value attribute of the options, you can significantly reduce the code necessary to do this: | |
| <option>B</option> | |
| to | |
| <option value="B">B</option> | |
| This will be helpful when you want to do something like: | |
| <option value="IL">Illinois</option> | |
| With that, the follow jQuery will make the change: | |
| $("select option[value='B']").attr("selected","selected"); | |
| If you decide not to include the use of the value attribute, you will be required to cycle through each option, and manually check its value: | |
| $("select option").each(function(){ | |
| if ($(this).text() == "B") | |
| $(this).attr("selected","selected"); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment