jquery - show textbox when checkbox checked

后端 未结 7 655
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 08:44

I have this form

7条回答
  •  攒了一身酷
    2021-01-21 09:30

    While you may need a JavaScript solution for other reasons, it's worth noting that this can be achieved with pure CSS:

    input + div.max_tickets {
        display: none;
    }
    
    input:checked + div.max_tickets {
        display: block;
    }
    

    JS Fiddle demo.

    Or, with jQuery, the simplest approach seems to be:

    // binds the change event-handler to all inputs of type="checkbox"
    $('input[type="checkbox"]').change(function(){
        /* finds the next element with the class 'max_tickets',
           shows the div if the checkbox is checked,
           hides it if the checkbox is not checked:
        */
        $(this).next('.max_tickets').toggle(this.checked);
    // triggers the change-event on page-load, to show/hide as appropriate:
    }).change();
    

    JS Fiddle demo.

    Reference:

    • CSS:
      • :checked pseudo-class.
    • jQuery:
      • change().
      • next().
      • toggle().

提交回复
热议问题