使用相同的功能扩展复选框选择列表

时间:2016-11-17 08:55:33

标签: javascript jquery checkbox

我有两个带复选框的选择列表,我想使用相同的函数showCheckboxes来管理它们以避免代码重复但是在选择正确的复选框列表时遇到问题,它不能通过id工作:

    <div class="multiselect">
    <div class="selectBox" id="select1" onclick="showCheckboxes(this.id)">
        <select>
            <option>Select deliverer</option>
        </select>
        <div class="overSelect"></div>
    </div>
    <div id="deliverer_checkboxes" style="height:100px;overflow:auto;">
      <% @deliverers.each do |deliverer|  %>
          <label for="<%= deliverer.id %>"><%= check_box_tag "deliverer_user_ids[]", deliverer.id %> <%= deliverer.name %></label>
      <% end %>
    </div>
  </div>

  <div class="multiselect">
    <div class="selectBox" id="select2" onclick="showCheckboxes(this.id)">
        <select>
            <option>Select shopper</option>
        </select>
        <div class="overSelect"></div>
    </div>
    <div id="shopper_checkboxes" style="height:100px;overflow:auto;">
      <% @shoppers.each do |shopper|  %>
          <label for="<%= shopper.id %>"><%= check_box_tag "shopper_user_ids[]", shopper.id %> <%= shopper.name %></label>
      <% end %>
    </div>
  </div>
  <%= f.submit 'Search', class: 'btn btn-success' %>
<% end %>
</div>

<script type="text/javascript">
var expanded = false;
  function showCheckboxes(clicked_id) {
      var checkboxes = document.getElementById(clicked_id);
      if (!expanded) {
          checkboxes.style.display = 'block';
          expanded = true;
      } else {
          checkboxes.style.display = 'none';
          expanded = false;
      }
  }
</script>

<style>
    .multiselect {
        width: 200px;
        float:left;
    }
    .selectBox {
        position: relative;
    }
    .selectBox select {
        width: 100%;
        font-weight: bold;
    }
    .overSelect {
        position: absolute;
        left: 0; right: 0; top: 0; bottom: 0;
    }
    #deliverer_checkboxes {
        display: none;
        border: 1px #dadada solid;
    }
    #deliverer_checkboxes label {
        display: block;
    }
    #deliverer_checkboxes label:hover {
        background-color: #1e90ff;
    }
    #shopper_checkboxes {
        display: none;
        border: 1px #dadada solid;
    }
    #shopper_checkboxes label {
        display: block;
    }
    #shopper_checkboxes label:hover {
        background-color: #1e90ff;
    }
</style>

2 个答案:

答案 0 :(得分:0)

而不是共享扩展变量,请检查&#34;展开&#34;直接从您单击的元素标记。一种方法是检查显示,因为你要切换它。

function showCheckboxes(clicked_id) {
    var checkboxes = document.getElementById(clicked_id);
    var display = checkboxes.style.display;
    checkboxes.style.display = display !== 'none' ? 'none' : 'block';
}

答案 1 :(得分:0)

我不确定您要做什么,但您获得所看到的行为的原因是:

1)&#34;点击两次&#34; - 当您展开框时,您已将expanded的初始值设置为false,因此您需要实际点击两次以切换隐藏。您可以通过将其设置为true最初

来更正此问题

2)以类似的方式重复使用代码存在类似的问题。您有多个expanded的{​​{1}}个变量。因此,您选择的selectBox将其值存储在该变量中,该值将应用于所有其他selectBox

您可以使用

等内容纠正这两个问题
selectBox

http://jsbin.com/lahulabilo/edit?html,js,output