我有一个 jQuery
将所有复选框值附加到一个 <input type="text"/>
中的脚本与 ','
,但是当我选中一个复选框时,它也会附加其他复选框中的所有值,而我只想附加我按顺序选中的值。
$('.check_list').on('change', function() {
var n = $(this).siblings('input:checkbox');
var nControl = $('.codeParc');
if ($(this).prop('checked')) {
n.prop('checked', true);
var vals = nControl.map(function() {
return $(this).val();
}).get().join(',');
} else {
n.prop('checked', false);
}
$('#test').val(vals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="cursor: pointer;" type="checkbox" value="" class="check_list"></input>
<input type="checkbox" class="codeParc" value="1"></input>
<input type="checkbox" class="codeParc" value="2"></input>
<input type="checkbox" class="codeParc" value="3"></input>
<input type="text" id="test" value=""></input>
此代码返回所有值 1,2,3
每当我选中一个复选框时,我需要的是选中一个复选框并仅显示他的号码,然后在选中时附加其余部分。
最佳答案
首先注意input
元素是自闭合的,所以它是 <input />
, 不是 <input></input>
.
一个更简单的方法是将选定的值映射到一个数组中并更新 input
的文本每次单击复选框时都会使用该数组中的值,如下所示:
$('.check_list').change(function() {
$('.codeParc').prop('checked', this.checked);
updateText();
});
$('.codeParc').change(function() {
$('.check_list').prop('checked', $('.codeParc').length == $('.codeParc:checked').length);
updateText();
});
function updateText() {
var checkedValues = $('.codeParc:checked').map(function() {
return this.value;
}).get();
$('#test').val(checkedValues.join(','));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="cursor: pointer;" type="checkbox" value="" class="check_list" />
<input type="checkbox" class="codeParc" value="1" />
<input type="checkbox" class="codeParc" value="2" />
<input type="checkbox" class="codeParc" value="3" />
<input type="text" id="test" value="" />
关于javascript - 在复选框的输入文本中一一追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39896810/