2012-09-23 9 views
10

5 개 이상의 옵션이있는 다중 선택 목록이 있으며 사용자가 선택한 옵션 선택 수를 계산하려고합니다.다중 선택 상자에서 선택 항목 수를 계산하십시오.

Java 스크립트를 사용하여 수행하는 방법은 무엇입니까?

나는 다음과 같은 시도했지만 나를 위해 작동하지 않았다 :

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

사전에 감사합니다.

+0

> var x = document.getElementById ("preference"). 개수; – coolmego

답변

21

foo은 선택 ID입니다. 정상적인 기능인 자바 스크립트를 사용하는 경우

:

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

당신은 jQuery를 사용하는 경우 :

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

thankyou, 그 workinkg 괜찮아요. 우리는 "체크 박스"에서 .checked 속성을 사용할 수있는 것처럼 for 루프를 사용하지 않고 선택 수를 확인할 수있는 속성이 있습니까? – coolmego

+0

@coolmego 아니요, 그런 자산은 없습니다. 'checkbox'의 경우,'checked' 속성을 사용하십시오. – xdazz

+1

기본부터 시작하는 자바 스크립트에 대한 좋은 자습서를 제안 해 줄 수 있습니다. – coolmego

1

사용 :selected 선택이 같은 :

당신은 얻을이 시도 할 수
$('#example option:selected').length; 
2

여러 개의 선택 상자 사용자 선택 옵션 개수 및 선택한 이름. < IE8이 문제가 아닌 경우 선택한 모든 옵션을 얻을 수 document.querySelectorAll("option:checked") 같은 한 줄을 수행 할 수 있습니다,이 링크를 http://jsfiddle.net/N6YK8/8/

function getCount(){ 
      var comboBoxes = document.querySelectorAll("select"); 
      var selected = []; 
      for(var i=0,len=comboBoxes.length;i<len;i++){ 
        var combo = comboBoxes[i]; 
        var options = combo.children; 
        for(var j=0,length=options.length;j<length;j++){ 
         var option = options[j]; 
         if(option.selected){ 
          selected.push(option.text); 
         } 
        } 
      } 
      alert("Selected Options '" + selected + "' Total Count "+ selected.length); 
     } 
0

을보십시오.

-1
function SelectPage(elem) 
{ 
    alert(elem); 
} 
<select id="page" name="section" onChange="SelectPage(this);" id="num"> 
    <option value="">Select Section</option> 
    <option value="1">Page-1</option> 
    <option value="2">Page-2</option> 
    <option value="3">Page-3</option> 
    <option value="4">Page-4</option> 
    <option value="5">Page-5</option> 
</select> 
+0

이 함수는 'var len = docment.getElementById ("num")에서도 사용할 수 있습니다. alert ("hello"+ len.length);' –

관련 문제