计算多选框中的选择数量 [英] count the number of selections in a multiple-select box

查看:106
本文介绍了计算多选框中的选择数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多选列表,其中有5个以上的选项,我想统计用户选择的选项的数量。



如何使用java脚本完成它?



我尝试了以下操作,但它对我无效:

  var x = document.getElementById(preference)。count; 

在此先感谢。

解决方案

假设 foo 是select的id。 如果使用普通的javasript :

  var options = document.getElementById('foo')。options,count = 0; 
for(var i = 0; i< options.length; i ++){
if(options [i] .selected)count ++;



$ b $ p
$ b

如果你使用jQuery:

  var count = $('#foo option:selected')。length; 


I have a multiple selection list which have more than 5 options, and i want to count the number of selection of the options selected by the user.

How to do it using java script?

I tried the following but it didn't work for me:

var x = document.getElementById("preference").count;

Thanks in Advance.

解决方案

Assume foo is the id of the select.

If you use normal javasript:

var options = document.getElementById('foo').options, count = 0;
for (var i=0; i < options.length; i++) {
  if (options[i].selected) count++;
}

If you use jQuery:

var count = $('#foo option:selected').length;

这篇关于计算多选框中的选择数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆