I want to set/select the text baed upon the texts I choose. e.g I have the following code that is not selecting the text but instead is adding another line to the option.
I have a dropdownlist with the following:
<select id="fruit"> <option value="">select here</option> <option value="1">apple</option> 开发者_JAVA技巧<option value="2">pineapple</option> <option value="3">orange</option><select>
$("#myList option:selected").text("pineapple");
$("#myList option:selected").text("select here");
How can I select the option based upon the text?
If you want to select one of the options based on its text, you could e.g. use: http://jsfiddle.net/pimvdb/HGLZE/.
Also you had different IDs, but that could be working depending on your scenario. I just changed it to be consistent with your HTML:
$("#fruit option").filter(function() { // filter options
return $(this).text() === "pineapple"; // only get option with text "pineapple" back
}).attr("selected", true); // set that option selected
$("#fruit option:selected").text("pineapple");
You had the wrong ID in you jQuery.
http://jsfiddle.net/ajthomascouk/f3k5X/
精彩评论