skip to Main Content

I have a simple div with multiple checkboxes in it. I want to look for any change in the checkbox to make an ajax query.
This code is not able to see the changes in those checkboxes. What is the right way to do it?

$(document).on('change', '#listfilters checkbox', function(e) {
        if(this.checked) {
            alert("changed");
          // checkbox is checked
        }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div id="listfilters">
    <p>
    <input type="checkbox" id="showall" name="showall" value=0>&nbsp;
    <label for="showall">Show All</label>
    </p>
    <p>
    <input type="checkbox" id="showfl" name="showfl" value=0>&nbsp;
    <label for="showfl">Filtered</label>
    </p>
</div>

2

Answers


  1. You need to qualify the checkbox part of the selector. Change it to #listfilters [type=checkbox]

    $(document).on('change', '#listfilters [type=checkbox]', function(e) {
            if(this.checked) {
                alert("changed");
              // checkbox is checked
            }
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    
    <div id="listfilters">
        <p>
        <input type="checkbox" id="showall" name="showall" value=0>&nbsp;
        <label for="showall">Show All</label>
        </p>
        <p>
        <input type="checkbox" id="showfl" name="showfl" value=0>&nbsp;
        <label for="showfl">Filtered</label>
        </p>
    </div>
    Login or Signup to reply.
  2. Instead of document, you can select directly your div for a quick/faster selector.

    $("#listfilters").on('change', 'input[type=checkbox]', function(e) {
            if(this.checked) {
                alert($(this).val());             
            }
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    
    <div id="listfilters">
        <p>
        <label for="showall"><input type="checkbox" id="showall" name="showall" value="showall">&nbsp;
        Show All</label>
        </p>
        <p>
        <label for="showfl"><input type="checkbox" id="showfl" name="showfl" value="Filtered">&nbsp;
        Filtered</label>
        </p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search