Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - show textbox when checkbox checked

I have this form

<form action="">
  <div id="opwp_woo_tickets">
    <input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][0][enable]">
    <div class="max_tickets">
        <input type="text" name="opwp_wootickets[tickets][0][maxtickets]">
    </div>

    <input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][1][enable]">
    <div class="max_tickets">
        <input type="text" name="opwp_wootickets[tickets][1][maxtickets]">
    </div>

    <input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][2][enable]">
    <div class="max_tickets">
        <input type="text" name="opwp_wootickets[tickets][2][maxtickets]">
    </div>
  </div>
</form>

As of now, I'm using this jquery code to show textbox when checkbox checked.

jQuery(document).ready(function($) {
   $('input.maxtickets_enable_cb').change(function(){
        if ($(this).is(':checked')) $('div.max_tickets').show();
        else $('div.max_tickets').hide();
    }).change();
});

It works fine, but it shows all textboxes when checked.

Can someone help me to fix it?

Here is the demo of my problem.

http://codepen.io/mistergiri/pen/spBhD

like image 445
PrivateUser Avatar asked Jul 16 '26 13:07

PrivateUser


2 Answers

As your dividers are placed next to your checkboxes, you simply need to use jQuery's next() method to select the correct elements:

if ($(this).is(':checked'))
    $(this).next('div.max_tickets').show();
else
    $(this).next('div.max_tickets').hide();

Updated Codepen demo.

From the documentation (linked above), the next() method selects:

...the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

Here we're selecting the next div.max_tickets element. However in your case just using next() with no parameters would suffice.

like image 82
James Donnelly Avatar answered Jul 19 '26 04:07

James Donnelly


Assuming markup will stay in same order can use next()

jQuery(document).ready(function($) {

    $('input.maxtickets_enable_cb').change(function(){
                $(this).next()[ this.checked ? 'show' : 'hide']();  
    }).change();
});
like image 41
charlietfl Avatar answered Jul 19 '26 02:07

charlietfl