我希望复选框值用“,”和“和”分隔,我有3个复选框,我想在div中显示这些值。例如,如果某人选择一个值,它将只是一个值;如果选择的值是两个,则它将被value1“和” value2分开;如果三个值,那么value1“,” value2“和”值3 >
$(".selective").change(function(e) {
var ValForDiv='';
var length = $('input.selective:checked').length;
var i=0;
$('input.selective:checked').each(function () {
i++;
var ThisVal = $(this).val();
if(i == 1){
ValForDiv += ThisVal;
}
else if(i == length){
ValForDiv += ThisVal + ' , ';
}
else if(i == length - 1){
ValForDiv += ThisVal + ' and ';
}
else{
ValForDiv += ' , ' + ThisVal.val();
}
});
$('.causinginjuriestospan').html(ValForDiv);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="label upperlowerback">
<ul>
<li>
<label>
<input id="chkforspcinjtoupper" type="checkbox" class="selective" name="chkforspcinjtoupper" value="upper"/>
<i></i>
<span>Upper</span>
</label>
</li>
<li>
<label>
<input id="chkforspcinjtomiddle" type="checkbox" class="selective" name="chkforspcinjtomiddle" value="middle" />
<i></i>
<span>Middle</span>
</label>
</li>
<li>
<label>
<input id="chkforspcinjtolower" type="checkbox" class="selective" name="chkforspcinjtolower" value="lower"/>
<i></i>
<span>Lower</span>
</label>
</li>
</ul>
</div>
<div class="causinginjuriestospan"></div>
答案 0 :(得分:0)
在回调函数开始时增加i
值时,它基本上是从1开始而不是从0开始,因此您必须检查i == length
而不是i == length - 1
。另外,您想在else
情况下在术语前添加逗号:
$(".selective").change(function(e) {
var ValForDiv='';
var length = $('input.selective:checked').length;
var i=0;
$('input.selective:checked').each(function () {
i++;
var ThisVal = $(this).val();
if(i === 1){
ValForDiv += ThisVal;
}
else if(i == length){
ValForDiv += ' and ' + ThisVal;
}
else{
ValForDiv += ', ' + ThisVal;
}
});
$('.causinginjuriestospan').html(ValForDiv);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="label upperlowerback">
<ul>
<li>
<label>
<input id="chkforspcinjtoupper" type="checkbox" class="selective" name="chkforspcinjtoupper" value="upper"/>
<i></i>
<span>Upper</span>
</label>
</li>
<li>
<label>
<input id="chkforspcinjtomiddle" type="checkbox" class="selective" name="chkforspcinjtomiddle" value="middle" />
<i></i>
<span>Middle</span>
</label>
</li>
<li>
<label>
<input id="chkforspcinjtolower" type="checkbox" class="selective" name="chkforspcinjtolower" value="lower"/>
<i></i>
<span>Lower</span>
</label>
</li>
</ul>
</div>
<div class="causinginjuriestospan"></div>