如果选择了父级,则选择子单选按钮,反之亦然
我有这样的情况:
现在我想强制检查冷杉到达组。 因此,如果有人选择data-smth="parent_1"
,则必须同时选择其中一个子项( data-parent="parent_1"
)。
例如,如果有人点击另一个组的孩子 ,则会选择其父级 。
所以这基本上都是两种方式。
我已尝试在jQuery中实现类似的function,但脚本很快就会混淆,然后用户就可以随心所欲地进行操作。 但是在开始时,没有尝试混合逻辑,它的工作非常好。
这是我目前的代码:
$(function() { $(document).on('click', '[data-smth]', function(){ $('[data-parent="' + $(this).attr('data-smth') + '"]:first').attr('checked', 'checked'); }) $(document).on('click', '[data-parent]', function(){ $('[data-smth="' + $(this).attr('data-parent') + '"]').attr('checked', 'checked'); }) })
想法将不胜感激。
使用.prop("checked", true);
而不是.attr('checked', 'checked');
工作得很好: http : //jsfiddle.net/fq1d2sar/
来自jQuery API :
属性与属性
在特定情况下,属性和属性之间的差异可能很重要。 在jQuery 1.6之前,
.attr()
方法有时在检索某些属性时会考虑属性值,这可能会导致行为不一致。 从jQuery 1.6开始,.prop()
方法提供了一种显式检索属性值的方法,而.attr()
检索属性。例如,应检索selectedIndex,tagName,nodeName,nodeType,ownerDocument,defaultChecked和defaultSelected,并使用
.prop()
方法进行设置。 在jQuery 1.6之前,这些属性可以使用.attr()
方法检索,但这不在attr
的范围内。 它们没有相应的属性,只是属性。
根据我的理解,你会想要这样的布局: http : //jsfiddle.net/0Lo1qwwf/2/
HTML:
-
-
-
JS:
$('input[type="radio"]').on('change', function() { $('.child').prop("checked", false); // Reset all child checkbox // Check if it's a parent or child being checked if ($(this).hasClass('parent')) { $('.child').prop('required', false); // Set all children to not required $(this).next('ul').find('.child').prop('required', true); // Set the children of the selected parent to required } else if ($(this).hasClass('child')) { $(this).prop("checked", true); // Check the selected child $(this).parent().parent().prev('.parent').prop('checked', true); // Check the selected parent } });
如果您遵循其他2个答案的建议,那么您当前的设置从function角度开始工作,但是因为您的所有孩子都具有相同的名称,这意味着他们无法明确地在表单中发布。
我已经将数据属性更改为类,因为检查类更简单。
我没有自动检查父节点的第一个子节点,而是将其设置为所需的子节点,如果它们没有提交表单,则应强制用户选择。 这只是我个人的偏好,因为强迫支票可能会让人大吃一惊。
希望JS中的注释解释其余部分,但如果您有不同的HTML DOM设置,则可能需要更改选择器以查找父项的子项和子项的父项。
这是我将使用的脚本:
$(document).on('change', '[data-smth]', function(){ $('[data-parent="' + $(this).attr('data-smth') + '"]:first').prop('checked', true); }) $(document).on('change', '[data-parent]', function(){ $('[data-smth="' + $(this).attr('data-parent') + '"]').prop('checked', true); })