2016-05-17 45 views
0
<select> 
    <option value="something else">James</option> 
    <option value="something else">John</option> 
</select> 

出于某种原因,我可以做$('select').val('something else'),因为value属性用于其他的东西。为了避免搞乱当前的工作,我该如何根据文本值选择元素?说我已经得到价值JamesJohn选择选项使用jquery基于文本

+0

上每个选项的值需要提交表单或获取选择值时是唯一的。 – aifrim

回答

1

您可以使用下面

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

的这将为您提供文字

2

$("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>

使用.filter()

DESCRIPT ion:将匹配元素的集合减少为匹配选择器或通过函数测试的元素。

1

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

1

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

0

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>

1

使用contains通过这样的文本选择的选项。

Fiddle Demo

堆栈示例:

$(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>