简体   繁体   中英

How to check number or checked checkboxes on load?

I want to check how many checkboxes are checked on load and not allow a specific number of checkboxes to be surpassed.

I have the following form:

<div id="checkbox" class="">
   <%= form.collection_check_boxes(:category_ids, Category.all, :id, :name, :multiple => true) do |c| %>
      <%= c.label class:"form-check-inline" do %>
        <%= c.check_box + c.text %>
      <% end %>
   <% end %>
</div>

Then this Javascript:

<script>
  $(document).on('turbolinks:load', function(){
      $('#checkbox input:checkbox').change(function () {
      var $cs=$('#checkbox input:checkbox:checked');
      if ($cs.length >= 4) {
        $('#checkbox input:checkbox:not(:checked)').attr("disabled", true);
      }
      else{
        $('#checkbox input:checkbox').attr("disabled", false);
      }
      });
    });
</script>

This works, although, it doesn't check on load. So someone could technically choose 4 off the first submit, then re update and check off another for 5, and so on.

This works but I am wondering if I can lessen this code into one:

  $(document).on('turbolinks:load', function(){
      $('#checkbox input:checkbox').change(function () {
      var $cs=$('#checkbox input:checkbox:checked');
      if ($cs.length >= 4) {
        $('#checkbox input:checkbox:not(:checked)').attr("disabled", true);
      }
      else{
        $('#checkbox input:checkbox').attr("disabled", false);
      }
      });
    });

    $(document).on('turbolinks:load', function(){
        var $cs=$('#checkbox input:checkbox:checked');
        if ($cs.length >= 4) {
          $('#checkbox input:checkbox:not(:checked)').attr("disabled", true);
        }
        else{
          $('#checkbox input:checkbox').attr("disabled", false);

        };
      });

Is this possible or is that the only option?

You can get rid of the duplication by triggering the event on one of the checkboxes:

 $(document).on('turbolinks:load', function(){
      $('#checkbox input:checkbox').change(function () {
          // business logic

         // now trigger event on first checkbox
      }).first().change()
 })

Alternatively, wrap all the business logic in a named function and call it on page load and pass it as reference to the change event listener

function updateCheckboxes() {
  var $cs = $('#checkbox input:checkbox:checked');
  if ($cs.length >= 4) {
    $('#checkbox input:checkbox:not(:checked)').attr("disabled", true);
  } else {
    $('#checkbox input:checkbox').attr("disabled", false);
  }
}

$(document).on('turbolinks:load', function() {
  updateCheckboxes();
  $('#checkbox input:checkbox').change(updateCheckboxes)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM