如果至少有一个所选项目具有自定义属性,如何隐藏HTML5分隔符?

时间:2015-12-07 21:00:39

标签: javascript jquery html html5 show-hide

我有一个包含多个HTML复选框的表单。我想隐藏一些分隔符,只有当至少一个选中的复选框具有名为“终结符”的自定义HTML5属性时。否则我会想要显示分隔符。

我尝试使用change()事件来检查是否有terminator属性。

这就是我所做的。

$("input[type='checkbox']").change(function(e) {

    var className = 'terminated_' + getContronId($(this).attr('name'));

    var existingElements = $('#survey-optional-controls').val().split('|') || [];


    //Hide all groups that have the class equal to className
    if( $(this).is(':checked') ){

        if( $(this).data('terminator') ){
            hideControls($(this), existingElements, className);
        }

    } else {

        showControls(existingElements, className);

    }

}).change();

函数hideControls将隐藏所需的输入。如果隐藏任何输入,函数showControls将显示所需的输入。

我的代码有点工作,但有一个问题,我无法找到解决方案。检查具有terminator属性的框并选中不具有terminator属性的框,然后“取消选中”不具有{{1}的框后,会出现此问题}属性。

首次选中带有terminator属性的框时,分隔符会按预期隐藏。

然后,当取消选中没有terminator属性的框时,它会显示应该隐藏的分隔符,因为我仍然有一个带有terminator属性的复选框。

如何解决此问题?

我创建了这个jFiddle来显示代码和问题。您可以通过跳转到jFiddle上的“1:b)更多问题”部分来重新创建问题,然后选中“红色”框,然后选中“绿色 - 终结者”框,最后取消选中“红色”框。您将看到下面的分隔符将如何显示在应隐藏的位置,因为“绿色 - 终结符”仍然被选中“

3 个答案:

答案 0 :(得分:1)

要确保仅在取消选中showControls属性的复选框时才会调用data-terminator

改变这个:

...

} else {
    showControls(existingElements, className);
}

...

} else if ($(this).is("[data-terminator]")) {
    showControls(existingElements, className);
}

更新了jsFiddle:http://jsfiddle.net/8yf0v3xt/10/

答案 1 :(得分:1)

您应该检查复选框的“已检查”状态,并在每次更改时设置data-terminator属性。

这样的东西
$("input[type='checkbox']").change(function(e) {
  var className = 'terminated_' + getContronId($(this).attr('name'));
  var existingElements = $('#survey-optional-controls').val().split('|') || [];

  var isTerminatorChecked = $("input:checkbox[data-terminator='Yes']").is(":checked");

  //Hide all groups that have the class equal to className
  if (isTerminatorChecked) {
    hideControls($(this), existingElements, className);
  } else {
    showControls(existingElements, className);
  }
});

Updated fiddle

答案 2 :(得分:-2)

下面的代码说'如果任何类型checkbox的输入正在改变'

$("input[type='checkbox']").change(function(e) { /*hide*/ }
else { /*show*/}

当您取消选中“红色”复选框this =“红色”时,红色未被选中,因此...会自动转到其中显示分隔符的其他参数