简体   繁体   中英

Select option using Jquery base on text

<select>
  <option value="something else">James</option>
  <option value="something else">John</option>
</select>

For some reason I can do $('select').val('something else') because the value attribute is used for other stuff. To avoid messing up the current working stuff, how do I select the element based on the text value? Says I already got the value James and John .

 $("select option").filter(function() { return $(this).text() == 'John'; }).prop('selected', true) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="something else">James</option> <option value="something else">John</option> </select> 

use .filter()

Description: Reduce the set of matched elements to those that match the selector or pass the function's test.

You can use the below

 $("#yourdropdownid option:selected").text();

This will provide you text

$('select').find('option[value="something else"]').prop("selected", true)

尝试$("select :selected").text();

Use contains for selecting the option by text like this.

Fiddle Demo

Stack Example:

 $(function() { var text = "John"; $("select option:contains(" + text + ")").attr('selected', 'selected'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <select> <option value="something else">James</option> <option value="something else">John</option> </select> 

 var selectText = function(elem, text) { if (elem && text) { elem.find('option').each(function() { var that = $(this); if (that.text() == text) { that.attr('selected', 'selected'); } }); } } selectText($('#target'), 'John'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="target"> <option value="something else">James</option> <option value="something else">John</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM