简体   繁体   中英

What is the best way for a lot of toggle forms

Here's the thing. I have 255 checkboxes in total that upon selecting open up a form. Here is an example:

图片

My initial approach was to toggle hidden forms with something like:

$("#machine1").click(function() {
    if( $(this).is(':checked')) {
        $(".containerTech").show();

    } else {
        $(".containerTech").hide();
    }
});

But, seeing the amount of forms, writing that 255 times just isn't right. Each form is slightly different. I'm no expert on JavaScript, I would really appreciate if someone could point me to the right direction on this.

Here's a fiddle: https://jsfiddle.net/z08cL3hm/

Tips:

  • Use a selector that's general.
  • Organize your checkboxes and forms appropriately (For example, each form can be placed next to the associated checkbox).
$("input[type='checkbox']").change(function(e) {
   $(this).next("form").toggle($(this).is(":checked"));
});

Toggle takes in Boolean to control the visible state of the element.

Note: I'm using change listener so that the logic works fine when checkbox is activated from keypress as well.

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