简体   繁体   中英

How to deselect multiple checkboxes at once when another checkbox is clicked in Firefox?

I mention Firefox in the title because my current implementation works perfectly in Chrome and IE but not in Firefox.

Currently I have two groups of checkboxes in one dropdown menu that are identified by two different classes, upperFilter and lowerFilter. What I want to happen is when a checkbox in the upperFilter group is clicked, any checkboxes that are already selected in the lowerFilter group are deselected and vice versa.

This is how I am currently handling this in javascript:

$("INPUT:checkbox").click(function () {

        if ($(this).hasClass("upperFilter") && $('INPUT:checked').filter('.lowerFilter').length > 0) {
            $('INPUT:checked').filter('.lowerFilter').click();
        } else if ($(this).hasClass("lowerFilter") && $('INPUT:checked').filter('.upperFilter').length > 0) {
            $('INPUT:checked').filter('.upperFilter').click();
        }

        // other stuff...

    });

Like I stated above, this works in Chrome and IE but in Firefox what happens is that when more than one checkbox is selected and you select a checkbox in the other group only one of the previously checked boxes get deselected.

What's strange is that I can select 3 boxes from upperFilter and then open up the Firebug console and type $('INPUT:checked').filter('.upperFilter').click(); and it deselects all 3 of them at once. Also, all of the JS is loaded at the end of the page, just FYI.

I have no idea why it would work in the console and not in-page.

Using .click is not the right way to go. Here's why:

You code says when some one clicks on the top, trigger the click event on the bottom (and vice versa) . So what's happening right now is someone clicks the top, and then you trigger a click on the buttom, which in turn is going to trigger a click on the top, which will then... you get the point.

Its hard to tell what you are trying to do and we can't see what happens on the page as different checkboxes are clicked, but you need to take advantage of both the click and change event.

  1. Keep the logic you currently have where click ing on the top toggles the bottom and vice versa.

  2. Instead of triggering the click event with ( .click ), trigger the change event. So replace this:

     $('INPUT:checked').filter('.lowerFilter').click(); 

    with this:

     $('INPUT:checked').filter('.lowerFilter').prop('checked', false).trigger('change'); 
  3. Then, elsewhere in your app, you need to listen for the "change" event on the checkboxes and update that part of your app accordingly.

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