我在jQuery中有以下脚本:
var cval5 = ' ';
$(':input[value^="ltrDataColumn"]').filter(':checked').each(function (index) {
var val = (this).value;
val = val.replace('ltrDataColumn', '');
cval5 = cval5 + val + '@@';
});
HTML:
<select multiple="multiple" style="width:370px">
<option value="ltrDataColumnred">Red</option>
<option value="ltrDataColumngreen">Green</option>
<option value="ltrDataColumnblue">Blue</option>
<option value="ltrDataColumnorange">Orange</option>
<option value="ltrDataColumnpurple">Purple</option>
<option value="ltrDataColumnyellow">Yellow</option>
<option value="ltrDataColumnbrown">Brown</option>
<option value="ltrDataColumnblack">Black</option>
</select>
在上面的列表中,我只选择黄色,但结果显示yellow@@yellow@@
而不是yellow@@
。
它将值加两次。我尝试了很多但是我无法复制它为什么每个值都添加两次。
答案 0 :(得分:2)
由于它是select
元素,您需要使用:selected filter not:checked
$('select option[value^="ltrDataColumn"]:selected').each(function (index) {
var val = this.value;
val = val.replace('ltrDataColumn', '');
cval5 = cval5 + val + '@@';
});
演示:Fiddle
另一种看待这种情况的方法是
var cval5 = $('select option[value^="ltrDataColumn"]:selected').map(function(){
return this.value.replace('ltrDataColumn', '');
}).get().join('@@');
演示:Fiddle
答案 1 :(得分:0)
您正在使用选择元素。所以,你的脚本应该是这样的:
var cval5 = ' ';
var select = $("select[multiple='multiple']");
var value = select.val();
if(value != null) {
for(var i=0; val=value[i]; i++) {
val = val.replace('ltrDataColumn', '');
cval5 = cval5 + val + '@@';
}
}
alert(cval5);
答案 2 :(得分:0)
首先,您混淆checked
和selected
并且您没有使用好的选择器,请查看控制台以查看输出,试试这个:
<强> HTML:强>
<select multiple="multiple" style="width:370px">
<option value="ltrDataColumnred" selected>Red</option>
<option value="ltrDataColumngreen" selected>Green</option>
<option value="ltrDataColumnblue">Blue</option>
<option value="ltrDataColumnorange" selected>Orange</option>
<option value="ltrDataColumnpurple">Purple</option>
<option value="ltrDataColumnyellow">Yellow</option>
<option value="ltrDataColumnbrown">Brown</option>
<option value="ltrDataColumnblack">Black</option>
</select>
JS:
var cval5 = ' ';
$('option[value^="ltrDataColumn"]:selected').each(function (index) {
var val = (this).value;
val = val.replace('ltrDataColumn', '');
cval5 = cval5 + val + '@@';
console.log(cval5);
});
<强>输出强>:
red@@
red@@green@@
red@@green@@orange@@