如何根据文本变量选择MultipleChoice选项

时间:2017-07-05 22:29:34

标签: javascript django multichoiceitems

我有一个MultipleChoiceField和一个变量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);

mystring

我可以使用jquery。谢谢

PS:偏离课程Mychoice1Mychoice2id_layer_select_x等选项。

我不想使用console.log(opt)=Object { length: 0, prevObject: Object[1] } ,我更喜欢不添加和归属。

问题是该复选框保持未选中状态

stack

1 个答案:

答案 0 :(得分:1)

您可以按照其中包含的文字过滤所有范围。然后,您可以获取前一个元素并进行检查。

&#13;
&#13;
$(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);
});
&#13;
<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>
&#13;
&#13;
&#13;