【问题标题】:Disabling multiple input field if a checkbox is checked for dynamic inputs and reenable it if no如果选中了动态输入的复选框,则禁用多个输入字段,如果没有,则重新启用它
【发布时间】:2016-10-12 16:39:48
【问题描述】:

我有几个动态输入字段和复选框,如果选中具有相似 id 值的复选框,我想禁用输入框

这是php代码:

   <table class="table table-striped">
                <thead>
                <tr>
                    <th>#</th>
                    <th>Description</th>
                    <th>Status</th>
                    <th>Comment</th>
                </tr>
                </thead>
                <tbody>

 foreach ($checks as $m => $check) {
    $item ="";
    $checkbox ="";
   $textinput ="";
   $displayx="";

if ($check->mandatory_customer == 1) { //mandatory customer checks
 $displayx .="<i style='color:red;'>*</i>";
  $item .=  $check->item.$displayx;
   $checkbox .='<input type="checkbox" class="1" id="'.$m.'"' ;
   $textinput .='<input type="text" class="1" id="'.$m.'"' ;

     } else { //not mandatory customer
    $item .=  $check->item;
   $checkbox .='<input type="checkbox" class="0" id="'.$m.'"' ;
 $textinput .='<input type="text" class="0" id="'.$m.'"' ;

    }

echo "<tr id='" . $m . "'>";
echo "<td>" . $m . "</td>";
echo "<td>" . $item . "</td>";
echo "<td>".$checkbox."</td>";
echo "<td>".$textinput."</td>";
echo "</tr>";
}
  ?>
     }

</tbody>

现在,如果选中复选框,我想禁用与复选框具有相同 ID 的输入框。我如何使用 jquery 完成此操作

【问题讨论】:

  • 不允许在多个元素上使用相同的 ID。您应该为每个元素设置唯一的 ID,并使用类或其他方式来识别相似的元素。
  • 我是 html 新手,除了 id 和 class 表单输入之外,我还可以使用其他标签吗
  • 不需要使用其他标签。请参阅我的答案以获取工作示例。

标签: javascript php jquery html checkbox


【解决方案1】:

正如我在评论中所述,不允许在多个元素上使用相同的 ID。您应该更新分配$checkbox$textinput 的行上的ID,以便分配唯一的ID 值,这也将帮助您检索另一端提交的值。将它们更改为 id="chk_'.$m.'"id="txt_'.$m.'" 就足够了。

此外,您似乎没有关闭输入标签。将/&gt; 添加到分配$checkbox$textinput 的行的末尾,如果不使用HTML 5,则添加&gt;

一旦你解决了这些问题,下面的 jquery 将为你工作:

$(function() {
  $('input[type=checkbox]').change(function() {
    if (this.checked) {
        $(this).closest('tr').find('input[type=text]').prop('disabled', true);
    } else {
        $(this).closest('tr').find('input[type=text]').prop('disabled', false);
    }
  });
});

演示: https://jsfiddle.net/BenjaminRay/nnphq559/

【讨论】:

【解决方案2】:
    $(document).ready(function () {
        $(":checkbox").on("change", function () {
            if ($(this).prop("checked"))
                $(":text#"+$(this).attr("id")).prop("disabled", "disabled");
            else
                $(":text#" + $(this).attr("id")).removeAttr("disabled");
        });
    });

【讨论】:

  • 无法禁用输入框
猜你喜欢
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
  • 2021-08-01
  • 2014-08-14
相关资源
最近更新 更多