jquery 判断select multiple是否有

 我来答
xiangjuan314
2016-05-13 · TA获得超过3.3万个赞
知道大有可为答主
回答量:2.9万
采纳率:0%
帮助的人:2748万
展开全部
<select multiple="multiple" style="width: 200px;" id="mymultiple">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>

</select>

使用原生的JavaScript 脚本只能够取得第一个选中的第一个的值
var z = document.getElementById("mymultiple");
alert(z.value)
可以通过轮训所有selected 的option 取得所有选中的数值
jQuery 或者第三方类库 会返回1,2,3,4 这样的值

jquery的实现如下:
通过判断select的 type 属性,如果是type: "select-multiple"(相对应的是select-one)
不是“select-one”,则轮训所有option,取得是selected 的option的数值,放到一个数组中

var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;

// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];

// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {

// Get the specific value for the option
value = jQuery( option ).val();

// We don't need an array for one selects
if ( one ) {
return value;
}

// Multi-Selects return an array
values.push( value );
}
}

return values;
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式