使用jquery(或javascript)根据点击的元素值设置下一个元素值



我有两个输入,一个是复选框,另一个是输入隐藏。我也有多个输入在一个页面

<input type="checkbox" class="comp-checkk" value="45164c0b-fc92-4f93-9c62-ea61336130eb">
<input type="hidden" class="comp-id" name="component_id[]" value="45164c0b-fc92-4f93-9c62-ea61336130eb"> 
<input type="checkbox" class="comp-checkk" value="45164c0b-fc92-4f93-9c62-ea61336130eb">
<input type="hidden" class="comp-id" name="component_id[]">
<input type="checkbox" class="comp-checkk" value="45164c0b-fc92-4f93-9c62-ea61336130eb">
<input type="hidden" class="comp-id" name="component_id[]">

我想用comp-checkk类的值来设置comp-id类的输入值。如果comp-id的值不为空,我想将comp-id设置为空,否则如果comp-id的值为空,我想将comp-id的值设置为comp-check

中的值我试过了:

$(document).on('change','.comp-checkk',function(){
if ($(this).next().val() != null) {
$(this).next().val(null);
} else {
$(this).next().val($(this).val());
}
});

如果comp-id不为空,则工作,但当值为空时,则不工作(没有发生任何事情)。我不知道我的代码出了什么问题。

我还在这里创建了JsFiddle

你必须检查不是nullnot empty

if ($(this).next().val() != null && $(this).next().val() != '') {
$(this).next().val(null);
} else {
$(this).next().val($(this).val());
}

相关内容

最新更新