I have a following dropdown:-
<select id="myselct">
<option value="0">One</option>
<option value="1">Two</option>
<option value="2">Three</option>
</select>
I wanna change the first value (value=0) from One to a different text.
Something like this that I tried didn't work:-
$("select#myselect option[value='One']").val("Change Value");
I have a following dropdown:-
<select id="myselct">
<option value="0">One</option>
<option value="1">Two</option>
<option value="2">Three</option>
</select>
I wanna change the first value (value=0) from One to a different text.
Something like this that I tried didn't work:-
$("select#myselect option[value='One']").val("Change Value");
Share
Improve this question
edited Aug 21, 2014 at 11:10
Steve
asked Aug 21, 2014 at 11:04
SteveSteve
2,5889 gold badges51 silver badges95 bronze badges
4 Answers
Reset to default 4Try,
$("#myselect option[value='0']").val("Change Value");
You are passing the text content as the value. That is the problem.
If you still want to use the text content then use :contains()
selector,
$("#myselect option:contains(One)").val("Change Value");
But note that :contains()
selector is a case sensitive one. Be careful while use it.
If you want to change the text of the option, then use,
$("#myselect option[value='0']").text("Change Value");
There are several ways to achieve what you need, considering this has been answered I will just add some additional ways to address the issue, maybe someone will find those useful.
All these will change the text of the first entry in the dropdown list:
//First three examples change the first child regardless of value;
$('#mySelect option:first-child').text("Change Value");
$('#mySelect').find('option').first().text("Change Value");
$('#mySelect option').eq(0).text("Change Value");
//Assuming the first element has a value of "0";
$('#mySelect option[value="0"]').text("Change Value");
If you'd like to change the value, not the text then you can use .val() instead of .text().
Note: I have changed the ID of your select in my example to 'mySelect', because there was a slight typo.
This will automatically change from given value to to be change value.
code below to replace one
with change value
$('#myselct option').each(function() {
$(this).text($(this).html().replace(/\bOne\b/g, 'Change Value'));
});
You can update the content of option with calling the .text("Change Value") function on the query result. Like so:
$("select#myselect option[value='1']").text("Change Value");
Alternatively you could query by option content:
$("select#myselect option:contains('One')").text("Change Value");
In the html you misspelled the id attribute of select.