Reputation: 3641
I have this select drop down box:
<select id="garden">
<option value="1">Flowers</option>
<option value="2">Shrubs</option>
<option value="3">Trees</option>
<option value="4">Bushes</option>
<option value="5">Grass</option>
<option value="6">Dirt</option>
</select>
I want to change the selection of this drop down by its option's name (i.e Trees).
Upvotes: 0
Views: 91
Reputation: 99
jQuery way:
$("select#garden option").each(function() {
if ($(this).text() == "Trees") $(this).attr("selected", "selected");
else $(this).removeAttr("selected");
});
Traditional JavaScript way:
var select = document.getElementById("#garden");
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].innerText == "Trees") select.options[i].selected = "selected";
else select.options[i].selected = false;
}
Upvotes: 1
Reputation: 4110
you could use jquery for that
var x = $('#my-select-id option:selected').text();
Upvotes: 0
Reputation: 2786
You can get value by the name with javascript in following way...
var val = document.getElementByName("garden").value;
Upvotes: 0