Javascript 如何在字段更新时选中复选框

Javascript 如何在字段更新时选中复选框,javascript,jquery,checkbox,input,Javascript,Jquery,Checkbox,Input,我正在制作一个包含10个字段和10个复选框的表单。在更新字段时,我希望选中相关复选框。我可以通过编写10个不同的ON change函数来实现它,但我正在寻找一种聪明的方法来实现它,而不是为各个字段编写10个不同的ON change函数 <input value="1" name="checkbox-1" id="checkbox-1" type="checkbox"/> <label for="checkbox-1"></label> <input ty

我正在制作一个包含10个字段和10个复选框的表单。在更新字段时,我希望选中相关复选框。我可以通过编写10个不同的ON change函数来实现它,但我正在寻找一种聪明的方法来实现它,而不是为各个字段编写10个不同的ON change函数

<input value="1" name="checkbox-1" id="checkbox-1" type="checkbox"/>
<label for="checkbox-1"></label>
<input type="text" value="" id="field-1" name="field-1">
<label class="form-label">Field 1</label>

<input value="1" name="checkbox-2" id="checkbox-2" type="checkbox"/>
<label for="checkbox-2"></label>
<input type="text" value="" id="field-2" name="field-2">
<label class="form-label">Field 2</label>

<input value="1" name="checkbox-3" id="checkbox-3" type="checkbox"/>
<label for="checkbox-3"></label>
<input type="text" value="" id="field-3" name="field-3">
<label class="form-label">Field 3</label>

$('#field-1').bind('change', () => {
    $('#checkbox-1').prop('checked', true);
});

$('#field-2').bind('change', () => {
    $('#checkbox-2').prop('checked', true);
});

$('#field-3').bind('change', () => {
    $('#checkbox-3').prop('checked', true);
});                                                 

字段1
字段2
字段3
$(“#字段-1”).bind('change',()=>{
$('#checkbox-1').prop('checked',true);
});
$(“#字段-2”).bind('change',()=>{
$('#checkbox-2').prop('checked',true);
});
$(“#字段-3”).bind('change',()=>{
$('#checkbox-3').prop('checked',true);
});                                                 

将iinput字段和复选框包装在一个div中,然后将复选框的逻辑添加到这些包装中

$('.checked input').find('input[type=text]')。on('change',function(){
$(this).closest('.checked input').find('input[type=checkbox]')).prop('checked',true);
});

您可以对其
id
中包含
字段的所有输入进行分组,并使用编号
id
选中相应的复选框:

$('input[id*=field]')。在('change',function()上{
$('#复选框-'+$(this).prop(“id”).split('-')[1]).prop('checked',true);
});

字段1
字段2
字段3
我建议您使用选择器查找所有字段并绑定
输入
处理程序。然后,当您能够处理它时,您必须找到相应的
复选框
,并选中它:

$('input[name^=“field-”])。在('input',function()上{
让fieldId=$(this.attr('name').slice(-1);
$(“#复选框-”+fieldId).prop('checked',true);
});

字段1
字段2

字段3
作为替代,您可以使用数据权限告诉输入要针对哪个复选框。我还设置了一个替代项,仅检查是否为空,或者设置一个替代项,以查找每个的前一个兄弟姐妹

$('input[type=text]')。关于('change',函数(事件){
让checkpair=$(this.data('targetpair');
$(checkpair).prop('checked',true);
//仅当不为空时才替换:
//$(checkpair).prop('checked',$(this.val().trim().length));
});
/*找到立即复选框同级的替换项
$('input[type=text]')。在('change',函数(事件){
$(this).prevAll('input[type=checkbox]).first().prop('checked',true);
});
*/

字段1
字段2
字段3