简体   繁体   中英

Checkboxs disabled with jquery not working as intended

i have some checkboxes that are displayed by doing a select in database that represents tables of a restaurant. Those tables that are already reserved i add them an disabled attribute. The problem with my script is that i only want to select three tables max and that means i need to add disabled atribute to the other to block them. and when i want to deselect those 3 already selected i need to remove the disabled attribute. Problem is that it removes the attribute from all tables even those that are reserved and selected from database.

Here is my script:
JSFIDDLE HERE

    <script type="text/javascript">
      var $checks = $(".table").change(function () {
      if ($checks.filter(":checked").length<3)
      {
        $(".formular").toggle($checks.filter(":checked").length>0);
        $checks.not(":checked").removeAttr("disabled");
        }
        else
        {
        $checks.not(":checked").attr("disabled", "disabled");
        }

    });

    </script>

Added a class .ignore to the input disabled from start and in js binding change event only to checkboxes without the ignore class as mentioned by @lolka_bolka

HTML

<input type="checkbox" class="bowling ignore" disabled/>
<input type="checkbox" class="bowling ignore" disabled/>
<input type="checkbox" class="bowling"/>
<input type="checkbox" class="bowling"/>

JS

var $checks = $(".bowling:not(.ignore)").change(function () {
    if ($checks.filter(":checked").length < 3) {
        $(".formular").toggle($checks.filter(":checked").length > 0);
        $checks.not(":checked").removeAttr("disabled");
    } else {
        $checks.not(":checked").attr("disabled", "disabled");
    }

});

:not(foo){} will match anything that isn't foo, including html and body. Source

Demo

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