【问题标题】:Checking a different checkbox hides input field选中不同的复选框会隐藏输入字段
【发布时间】:2013-12-05 06:11:13
【问题描述】:

我有一个仅在选中“其他”选项时显示的输入字段。当我取消选中“其他”复选框时,输入字段会淡出,但我也希望输入字段淡出,而不是取消选中“其他”复选框,而是选中同一组的另一个复选框。因此,除非选中“其他”,否则“其他”输入字段不应可见。我的 javascript 部分工作,但是当我选中另一个复选框时,“其他”输入字段仍然可见。

HTML

<input type="checkbox" id="residence_check" name="found"/>
<label for="residence_check">
    Residence
</label>
<input type="checkbox" id="tradeshow_check" name="found"/>
<label for="tradeshow_check">
    Tradeshow
</label>
<input type="checkbox" id="office_check" name="found"/>
<label for="office_check">
    Office Building
</label>
<input type="checkbox" id="check_other" value="found_other" name="found"/>
    <label for="check_other">
    Other
</label>
<input type="text" id="check_input" placeholder="Other"/>

Javascript

$('#check_other').change(function() {
    if($(this).is(":checked")) {
        $('#check_input').fadeIn();
    } else {
        $('#check_input').fadeOut('fast');
            }
});

【问题讨论】:

    标签: javascript jquery checkbox hide unchecked


    【解决方案1】:

    如果你想在复选框中获得一些乐趣,你可以试试这个:

    function showHideOtherInput() {
    console.log($(this)[0]==$('#check_other')[0]);
            var shouldShow=$('[id$="_check"]:checked').length===0 && $('#check_other').prop('checked');
            console.log(shouldShow);
        if(shouldShow) {
            $('#check_input').fadeIn();
        } else {
            $('#check_input').fadeOut('fast');
                }
    }
    $('#check_input').hide(); //since nothing is selected at this point just hide the input
    $('#check_other').change(showHideOtherInput);
    //for each XXXX_check checkbox trigger the show or hide function
    $('[id$="_check"]').each(function(ix,el){$(el).change(showHideOtherInput)});
    

    希望这对你有用。 :)

    【讨论】:

      【解决方案2】:

      从我从您的用例中收集到的信息是,您不想使用复选框,而是使用单选按钮。如果是这种情况,这将是实现您想要的好方法:

      http://jsfiddle.net/AeP58/1/

      $('input[type=radio]').on('change', function() { //event on all radio buttons
          if($(this).attr('id') == 'check_other' && $(this).prop('checked')) {
              $('#check_input').fadeIn();
          } else {
              $('#check_input').fadeOut('fast');
          }
      });
      

      如果您确实需要复选框,您可以稍微更改代码并可能得到您想要的。

      【讨论】:

      • 我刚改成 input[type=checkbox] 效果很好。谢谢!
      猜你喜欢
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      相关资源
      最近更新 更多