【发布时间】:2021-10-22 08:02:55
【问题描述】:
我正在寻找解决方案,如何更改多个填充的复选框 - 使用 JavaScript 帮助输入字段值。如果选中复选框,如何将值从 yes 更改为 no 和 no 到 yes。这是我使用的部分代码:
html表单:
<form method="post" action="" autocomplete="off" id="form">
<p class="lable_2">Select place</p>
<span class="boxx dothetrick" id="df3">
<select data-skip-name="true" name="pl[]">
<option value="">select place</option>
<option value="Berlin">Berlin</option>
<option value="London">London</option>
<option value="Barcelona">Barcelona</option>
</select>
<label for="">Date: </label><input type="date" name="pl[]" value="iesndat">
<label for="">Yes/No: </label><input type="checkbox" name="pl[]" id="trick" value="no">
<button type="button" name="add3" id="add3" class="btn btn-success">+</button>
</span>
</form>
javascript:
<script>
$(document).ready(function(){
$('.dothetrick input[type="checkbox"]').change(function() {
if ($(this).is(":checked")) {
document.getElementById("trick").value = "yes";
} else
document.getElementById("trick").value = "no";
});
var i = 1;
$('#add3').click(function(){
i++;
$('#df3').append('<span id="row'+i+'"><br><select data-skip-name="true" name="pl[]"><option value="">select place</option><option value="Berlin">Berlin</option><option value="London">London</option><option value="Barcelona">Barcelona</option></select> <label>Date: </label><input type="date" name="pl[]" value="iesndat"><label> Yes/No: </label><input type="checkbox" name="pl[]" id="trick'+i+'" value="no"> <button name="remove" id="'+i+'" class="btn btn-danger btn_remove3">-</button></span>');
});
$(document).on('click','.btn_remove3', function(){
var button_id = $(this).attr("id");
$("#row"+button_id+"").remove();
});
});
</script>
这部分工作完美:
$('.dothetrick input[type="checkbox"]').change(function() {
if ($(this).is(":checked")) {
document.getElementById("trick").value = "yes";
} else
document.getElementById("trick").value = "no";
});
但是如何使这部分 js 代码工作,使填充的复选框值从 no 更改为 yes 和 yes 到 no:
var i = 1;
$('#add3').click(function(){
i++;
$('#df3').append('<span id="row'+i+'"><br><select data-skip-name="true" name="pl[]"><option value="">select place</option><option value="Berlin">Berlin</option><option value="London">London</option><option value="Barcelona">Barcelona</option></select> <label>Date: </label><input type="date" name="pl[]" value="iesndat"><label> Yes/No: </label><input type="checkbox" name="pl[]" id="trick'+i+'" value="no"> <button name="remove" id="'+i+'" class="btn btn-danger btn_remove3">-</button></span>');
});
这个想法是这样的:
var i = 1;
$('#row'+i).change(function() {
if ($(this).is(":checked")) {
i++;
document.getElementById("trick"+i).value = "yes";
} else
i++;
document.getElementById("trick"+i).value = "no";
});
自己找不到答案。我希望这个想法很清楚,有人可以帮助我!
【问题讨论】:
-
我的想法是否正确:最初复选框看起来像“否:□”,但如果用户选中它,它会变为“是:☑”?这不是复选框工作的标准方式,并且很容易导致用户混淆。这些看起来也没有必要,因为如果用户不想要地点+日期组合,他们只需按减号按钮即可删除该组合。
-
感谢您的回答。这些字段具有不同的含义,我只是发布示例以供参考。我需要的是:如果复选框从“否”选中为“是”,则更改新的填充字段值,并将数据放入 mysql,如果未选中复选框,将其更改回“否”,并更新 mysql 中的数据。就是这个想法。
标签: javascript html jquery ajax checkbox