jquery - 选中复选框时显示文本框

Gir*_*iri 3 html javascript jquery

我有这个表格

<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>
Run Code Online (Sandbox Code Playgroud)

截至目前,我正在使用此jquery代码在复选框选中时显示文本框.

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

它工作正常,但它会在选中时显示所有文本框.

有人可以帮我解决吗?

这是我的问题的演示.

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

Jam*_*lly 7

当你的分隔符放在你的复选框旁边时,你只需要使用jQuery的next()方法来选择正确的元素:

if ($(this).is(':checked'))
    $(this).next('div.max_tickets').show();
else
    $(this).next('div.max_tickets').hide();
Run Code Online (Sandbox Code Playgroud)

更新了Codepen演示.

从文档(上面链接),该next()方法选择:

...匹配元素集中每个元素的紧随其后的兄弟.如果提供了选择器,则仅当它与该选择器匹配时,它才会检索下一个兄弟.

在这里,我们选择下一个div.max_tickets元素.但是在你的情况下,只使用next()没有参数就足够了.