[英]How to change the input fields name in a row on checkbox click
更改選中的復選框行的輸入字段名稱
注意:“類型”字段可能在每一行中存在或不存在。
就像存在name []和type []字段一樣,將name都更改為name1 []和type1 []。 或者如果type []不存在,則更改name []字段的名稱。
$(document).ready(function() { $(".click1").on('change', function() { if($(this).is(":checked")) { alert('checked') } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li id="row_3"> <div class="col-md-6"> <input type="text" name="name[]"> <input type="text" name="type[]"> <input type="checkbox" name="click" class="click1"> </div> </div> </li>
您應該.find('input[name^="type"]')
並檢查它是否存在,如果存在,則將其他輸入元素的name
更改為name1
。 下面是更新的代碼:
$(document).ready(function() { $(".click1").on('change', function() { if ($(this).is(":checked")) { if ($(this).parent().find('input[name^="type"]').length) { $(this).parent().find('input[name^="name"]').prop('name', 'name1[]'); } } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li id="row_3"> <div class="col-md-6"> <input type="text" name="name[]"> <input type="text" name="type[]"> <input type="checkbox" name="click" class="click1"> </div> </li>
向兩個元素添加id
,以便您可以在代碼中輕松訪問它們。
<input type="text" id="name" name="name[]">
<input type="text" id="type" name="type[]">
並且,在您的jQuery中,更改名稱,如下所示:
$(document).ready(function() {
$(".click1").on('change', function() {
if($(this).is(":checked")) {
$("#name").attr("name", "name1[]");
$("#type").attr("name", "type1[]");
}
});
});
好消息是,如果刪除#type
字段, $("#type")
將返回一個空集,並且您將不對其執行任何操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.