【问题标题】:Dynamic checkboxes based on drop down select in JqueryJquery中基于下拉选择的动态复选框
【发布时间】:2014-09-17 22:24:31
【问题描述】:

我正在尝试根据 Jquery 中的选择值隐藏复选框。例如,如果用户选择 1,它会隐藏复选框 1,依此类推。

谢谢

HTML:

<label for="dropdown">Dropdown:</label></th><td><select id="dropdown" name="dropdown">
<option value="" disabled="disabled" selected="selected">Please select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>

</select>
<div id='checkbox'>
<label for="id_checkbox_0"><input id="id_checkbox_0" name="checkbox" type="checkbox" value="1" /> 1</label>
<label for="id_checkbox_1"><input id="id_checkbox_1" name="checkbox" type="checkbox" value="2" /> 2</label>
<label for="id_checkbox_2"><input id="id_checkbox_2" name="checkbox" type="checkbox" value="3" /> 3</label>
<label for="id_checkbox_3"><input id="id_checkbox_3" name="checkbox" type="checkbox" value="4" /> 4</label>
</div>

JQuery:

 $( document ).ready(function() {  
    $('#checkbox').hide();
    $("#dropdown").change(function() {
        $('#checkbox').show();
        var index = $(':selected', this).index();
        $('input:(#id_checkbox_'+index+')').hide(); 
        $('input:not(#id_checkbox_'+index+')').show();

     });

 });

JSFiddle 链接:

http://jsfiddle.net/ffs408u6/4/

【问题讨论】:

    标签: jquery html checkbox


    【解决方案1】:

    我的建议是将每个label/checkbox 放在一个div 中,该div 的数据属性对应于select 的值:

    <div data-id="1">
      <label for="id_checkbox_0">
        <input id="id_checkbox_0" name="checkbox" type="checkbox" value="1" /> 1
      </label>
    </div>
    

    然后让你的 jQuery 看起来像这样:

    $("#dropdown").change(function() {
        var index = $(this).val();
        $("[data-id]").show();
        $("[data-id=" + index + "]").hide();
        $('#checkbox').show();
     });
    

    Fiddle here

    【讨论】:

      【解决方案2】:

      我建议,尽管您已经接受了答案:

      var checkboxes = $(’input[type="checkbox"]').hide();
      $('#dropdown').on('change', function(){
          var select = this;
          checkboxes.show().filter(function() {
              return this.value !== select.value;
          }).hide();
      });
      

      如果您想隐藏父、标签、元素(包括子输入):

      var checkboxes = $(’input[type="checkbox"]').hide();
      $('#dropdown').on('change', function(){
          var select = this;
          checkboxes.show().filter(function() {
              return this.value !== select.value;
          }).parent().hide();
      });
      

      【讨论】:

      • 你的意思是 $('input[type="checkbox"]').hide();?它对我不起作用:(。
      猜你喜欢
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 2022-01-05
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多