0

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>

1
  • 2
    change your selector to $(document).on('change', '#listfilters input[type=checkbox]', function(e) { Commented Dec 31, 2020 at 6:40

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.