我的智慧结束了这个。
当我单击一个复选框时,我想在下面的输入中将复选框的ID添加到逗号分隔的字符串中。我有这个工作,但我不能做的是删除ID及其逗号,如果它已经存在于输入字段中(检查和取消选中)。
简单的形式。
<form>
<input class="iteminput" type="checkbox" value="1" id="1" name="<?php echo $title; ?>">
<input class="iteminput" type="checkbox" value="2" id="2" name="<?php echo $title; ?>">
<input class="iteminput" type="checkbox" value="3" id="3" name="<?php echo $title; ?>">
<!-- Note that this field may or may not have an existing string of ID's (1,2,3) from previous saves -->
<input type="text" id="excludelist" value="<?php echo $saved-string; ?>">
</form>
jQuery(document).ready(function(){
jQuery('.iteminput').on('click', function(){
var id = jQuery(this).attr('ID');
var string = jQuery('#excludelist').val();
var newstring = string + id + ',';
jQuery('#excludelist').val(newstring);
})
})
答案 0 :(得分:1)
您可以获取输入框的值,并使用split方法将ID字符串拆分为数组。此时,您可以检查您要查找的ID是否在该阵列中。例如:
const id = 3;
const inputValue = $('input[type=text]').val();
// Split the IDs into an array by comma.
const currentIds = inputValue.split(',');
if (currentIds.indexOf(id) === -1) {
// ID has not yet been added to the input box.
// We can add it to the array here, and
// update it later.
currentIds.push(id);
} else {
// ID is in the current list of IDs. We
// can remove it like this:
currentIds.splice(currentIds.indexOf(id), 1);
}
// Finally, we can reset the input string
// with the new values we set above.
$('input[type=text]').val(currentIds.join(','));
请参阅:
答案 1 :(得分:1)
为什么不重建它?
var $iteminputs = $('.iteminput');
$iteminputs.on('change', function(){
var ids = $.map($iteminputs.filter(':checked'), function(element){ return element.id; });
$('#excludelist').val(ids.join(','));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="iteminput" type="checkbox" value="1" id="1" name="title1">
<input class="iteminput" type="checkbox" value="2" id="2" name="title2" checked>
<input class="iteminput" type="checkbox" value="3" id="3" name="title3" checked>
<!-- Note that this field may or may not have an existing string of ID's (1,2,3) from previous saves -->
<input type="text" id="excludelist" value="2,3">
&#13;