gpt4 book ai didi

jquery - 使用 jquery 将选定的复选框放入文本框中

转载 作者:行者123 更新时间:2023-12-01 03:59:34 26 4
gpt4 key购买 nike

如何使用 jquery 将选定的复选框按照用户选择的顺序放入文本框中?每次我选择随机复选框时,文本框的值都取决于复选框列表的模式。这是我的代码:

<label>Favorite activities and areas: (Please check the box in order of priorities)</label>
<input type="checkbox" class="chckbox" value="C"/>C
<input type="checkbox" class="chckbox" value="C#"/>C#
<input type="checkbox" class="chckbox" value="PHP"/>PHP
<input type="checkbox" class="chckbox" value="Javascript"/>Javascript
<input type="checkbox" class="chckbox" value="Java"/>Java
<hr>
<input type="text" id="subject_areas" placeholder="Selected Checkboxes" disabled>

这是我的 jquery 代码:

<script type="text/javascript">
$(document).ready(function(){
$('.chckbox').click(function(){
var text = "";
$('.chckbox:checked').each(function(){
text += $(this).val() + ', ';
});
text = text.substring(0,text.length-2);
$('#subject_areas').val(text);
});
});
</script>

例如,我选择 PHP,然后选择 C,那么文本框的值为“C,PHP”,这是错误的。我想要的值是“PHP,C”。请帮我。谢谢。

最佳答案

一种方法是设置一个数组变量集,根据 checked 属性添加或删除该变量

$(document).ready(function(){
//Set your array variable
var checkboxValues = [];

$('.chckbox').change(function(){
var $this = $(this),
val = $this.val();
//Check if checkbox is checked
if($this.prop('checked')){
//Add value to array
checkboxValues.push(val);
}else{
//Get index of current value
var index = checkboxValues.indexOf(val);

//Remove value from array
checkboxValues.splice(index,1);
}

//Use join() for a "cleaner" approach (no trimming required)
$('#subject_areas').val(checkboxValues.join(', '));

});
});

关于jquery - 使用 jquery 将选定的复选框放入文本框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51412930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com