2017-07-05 11 views
0

私はなMultipleChoiceFieldと変数my_choice = 'mystring'テキスト変数に基づいて、多肢選択法オプションを選択する方法

私はここでmy_choice

htmlにオプションの相対チェックしたい持っている:

ul id="id_layer_select"><li><label for="id_layer_select_0"><input checked="checked" id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li> 
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li> 
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul> 

ここに私をjavascript

var my_choice = 'mystring' 
var opt = $("#id_layer_select option"); 
opt.filter("[value=my_choice]").attr("selected", true); 

jqueryを使用できます。オフコースmystring私はid_layer_select_xを使いたくないと私は追加して、属性ではないことを好むオプションMychoice1またはMychoice2かなど

です:

PSはありがとうございます。

問題は、チェックボックスのチェックを外し滞在し、

console.log(opt)=Object { length: 0, prevObject: Object[1] } 

答えて

1

あなたは、彼らが含まれているテキストがすべてのスパンをフィルタリングすることができるということです。これで前の要素を取得してチェックすることができます。

$(document).ready(function() { 
 
    var txt = "Mychoice3"; 
 
    
 
    
 
    var labelMatchingTxt = $('#id_layer_select span').filter(function(i, el) { 
 
    return txt === el.childNodes[0].nodeValue; // avoiding DOM reselection. 
 
    }).prev().prop('checked', true); 
 
});
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head> 
 

 
<body> 
 

 
<ul id="id_layer_select"><li><label for="id_layer_select_0"><input id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li> 
 
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li> 
 
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul> 
 
</body>

+0

あなたは正しいですが、まだ動作しません。 Console.log(opt)=オブジェクト{length:0、prevObject:Object [1]}。それは私に間違って見える。 – fabio

+0

アップデートをご覧ください –

関連する問題