我创建了一个将所有已检查项目放入文本区域的函数..但我的问题是已检查项目的显示已被编入索引。
例如:
[x] checkbox1(第二个刻度)
[x]复选框2(第一个勾号)
[x] checkbox3(第三个刻度)
现在显示就像这样
checkbox1 - > checkbox2 - > checkbox3
它应该是checkbox2 - > checkbox1 - > checkbox3
这是功能:
function checkTick()
{
$('input[type=checkbox]').change(function () {
var selectedvalue=[];
$(":checkbox:checked").each(function(){
selectedvalue.push($(this).attr("value"));
});
document.getElementById('txtSignOff').value = selectedvalue.join("->");
});
}
答案 0 :(得分:3)
全局范围:在全局范围内设置变量selectedvalue
。而不是按下每个复选框值,只需按下当前复选框值。
取消选中时的弹出值:取消选中/取消选中复选框时,如果数组中的所有值都应该是不同的,则应从数组中弹出相应的值。
var selectedvalue=[];
$('input[type=checkbox]').change(function () {
//If checked then push the value
if($(this).is(":checked")){
selectedvalue.push($(this).attr("value"));
}else{
//This is what pops the value from the array when the checkbox is unchecked.
selectedvalue.splice(selectedvalue.indexOf($(this).attr("value")),1);
}
document.getElementById('txtSignOff').value = selectedvalue.join("->");
});
功能阻止:您无需将其阻止到函数checkTick
中。当事件发生时,jQuery实用程序会为您提供这样的东西。
答案 1 :(得分:0)
您做得正确,但您的变量被覆盖,因此它的值不正确。让它全球化
var selectedvalue=[];
另一个要点是"这里不需要为每个复选框制作.e;"
现在功能
function checkTick()
{
$('input[type=checkbox]').change(function () {
selectedvalue.push($(this).attr("value"));
document.getElementById('txtSignOff').value = selectedvalue.join("->");
});
}