jQuery:根据多个复选框组成的数组中的特定选中复选框来切换字段集 [英] jquery: toggle a fieldset based upon a specific checked checkbox in an array of multiple checkboxes
问题描述
使用jquery,给定多个复选框,如果选中/未选中特定复选框,我们将如何打开/关闭字段集? (可能会选中多个复选框,因为它是多个)
Using jquery, given multiple checkboxes, how please would we toggle a fieldset on/off if a particular checkbox is checked/ unchecked? (more than one checkbox may be chosen as this is multiple)
我尝试将':checked'和'jQuery.inArray'与toggle()一起使用,但还没有运气. 不带脚本的HTML示例:
I've tried using ':checked' and 'jQuery.inArray' together with toggle() but no luck yet. Example HTML without the script:
<form>
Which food group do you like?
<input type="checkbox" name="nutrition[]" value="Fruit">
<input type="checkbox" name="nutrition[]" value="Vegetables">
<input type="checkbox" name="nutrition[]" value="Sweets">
<!-- show this input (toggle on/off) only if 'Fruit' is one of the checked boxes-->
<fieldset id="someid" style="display:none;>
You chose Fruit! Name one fruit: <input type="text" name= "afruit" />
</fieldset>
</form>
?
这是基于Jason P的答案的完整html +脚本,使用id作为选择器:
here is the complete html + script based on Jason P's answer, using id as selector:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
window.onload = function() {
$('#fruitid').change(function(e) {
$('#someid').toggle(this.checked);
});
};
</script>
</head>
<body>
<form>
Which food group do you like?
<input type="checkbox" name="nutrition[]" value="Fruit" id="fruitid">
<input type="checkbox" name="nutrition[]" value="Vegetables">
<input type="checkbox" name="nutrition[]" value="Sweets">
<!-- show this input (toggle on/off) only if 'Fruit' is one of the checked boxes-->
<fieldset id="someid" style="display:none;">
You chose Fruit! Name one fruit: <input type="text" name= "afruit" />
</fieldset>
</form>
</body>
</html>
推荐答案
$('input[value="Fruit"]').change(function(e) {
$('#someid').toggle(this.checked);
});
向水果"复选框添加类或ID可能是一个好主意,以便您可以使用更好的选择器.
Might be a good idea to add a class or id to the "Fruits" checkbox so you can use a better selector.
这篇关于jQuery:根据多个复选框组成的数组中的特定选中复选框来切换字段集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!