简体   繁体   中英

Showing a text input when checkbox is clicked - Jquery

I'm having an issue with this code and I can't figure out whey it's not working. Essentially, when a checkbox is clicked, the text field in the same li should show up.

I don't want a "hide / show", since this will populate the array with additional fields, so i'm looking at making it fill the div with a new input if the checkbox is selected.

Any ideas where I'm running into an issue?

Here's my html:

<ul>
    <li class="practice"><label><input type="checkbox" value="Practice 1" class="input_control" name="practice_areas[id][name]" /> Practice 1</label> <div class="showOrder"></div></li>
    <li class="practice"><label><input type="checkbox" value="Practice 2" class="input_control" name="practice_areas[id][name]"  /> Practice 2</label> <div class="showOrder"></div></li>
    <li class="practice"><label><input type="checkbox" value="Practice 3" class="input_control" name="practice_areas[id][name]"  /> Practice 3</label> <div class="showOrder"></div></li>
    <li class="practice"><label><input type="checkbox" value="Practice 4" class="input_control" name="practice_areas[id][name]"  /> Practice 4</label> <div class="showOrder"></div></li>
    <li class="practice"><label><input type="checkbox" value="Practice 5" class="input_control" name="practice_areas[id][name]"  /> Practice 5</label> <div class="showOrder"></div></li>                 
</ul>

Here's my Javascript:

<script>
jQuery('li.practice').each(function() {
    jQuery(".input_control", this).click(function() {
        jQuery('.showOrder', this).html('<label>Order: <input type="text" size="2" name="practice_area[id][order]" value="" /></label>');
    });
});

</script>

You were incorrectly using your .input_control as context for locating your .showOrder , I changed your code to use your li.practice as context, so do as follows:

jQuery('li.practice').each(function() {
    var li = this;
    jQuery(".input_control", this).click(function() {
        jQuery('.showOrder', li).html('<label>Order: <input type="text" size="2" name="practice_area[id][order]" value="" /></label>');
    });
});

You are misusing $(selector, context) , the .showOrder element is not within the context of clicked element.

$('li.practice .input_control').change(function(){
    var $target = $(this).closest('li').find('.showOrder');
    if (this.checked) {
        $target.html('<label>Order: <input type="text" size="2" name="practice_area[id][order]" value="" /></label>');
    } else {
        $target.empty();
    }
});

http://jsfiddle.net/Qh6Fq/1/

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