[英]Select option using Jquery base on text
<select>
<option value="something else">James</option>
<option value="something else">John</option>
</select>
由于某些原因,我可以执行$('select').val('something else')
因为value属性用于其他内容。 为了避免弄乱当前的工作内容,如何根据文本值选择元素? 说我已经有了James
和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>
描述:将匹配元素的集合减少为与选择器匹配或通过功能测试的元素。
您可以使用以下
$("#yourdropdownid option:selected").text();
这将为您提供文字
$('select').find('option[value="something else"]').prop("selected", true)
尝试$("select :selected").text();
使用contains
可以通过这样的文本选择选项。
堆栈示例:
$(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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.