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。谢谢

PS:Off coursemystring是一个选项Mychoice1Mychoice2等等。

我不想使用 theid_layer_select_x并且我更喜欢不添加和属性。

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

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

1 回答 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>

于 2017-07-05T22:37:10.977 回答