2016-05-17 46 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>