Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...