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

あなたは、これはあなたが

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テキスト提供します

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

を使用することができますion:一致する要素のセットをセレクタに一致するものに減らすか、関数のテストに渡します。

1

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

1

このようなテキストでオプションを選択するために使用contains$("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

てみてください。

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>

関連する問題