1. 程式人生 > >JS jQuery分別獲取選中的複選框值

JS jQuery分別獲取選中的複選框值

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<style>

</style>
<title>JS獲取複選框被選中的值</title>
</head>
<body>
<input type="checkbox" name="aihao" value="0" />0&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="1" />1&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="2" />2&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="3" />3&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="4" />4&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="5" />5&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="6" />6&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="7" />7&nbsp;&nbsp;
<input type="button" onclick="chk()" value="提  交" />
</body>
</html>
 總共有八個checkbox和一個按鈕,點選“提交”按鈕後可以知道當前所選中的複選框的value值,下面是JS程式碼,
<script src="jquery.js"></script><!--這是載入jquery.js檔案,如果不使用jquery可以去掉-->
<script>
function chk(){
  var obj=document.getElementsByName('aihao');  //選擇所有name="aihao"的物件,返回陣列
  //取到物件陣列後,我們來迴圈檢測它是不是被選中
  var s='';
  for(var i=0; i<obj.length; i++){
    if(obj[i].checked) s+=obj[i].value+',';  //如果選中,將value新增到變數s中
  }
  //那麼現在來檢測s的值就知道選中的複選框的值了
  alert(s==''?'你還沒有選擇任何內容!':s);
}

function jqchk(){  //jquery獲取複選框值
  var s='';
  $('input[name="aihao"]:checked').each(function(){
    s+=$(this).val()+',';
  });
  alert(s==''?'你還沒有選擇任何內容!':s);
}
</script>
 點選“提交”後,可以得到正確的選擇值了,但是後面多一個,(英文逗號),這個可以檢測一下再用substring去除,或者獲取到複選框選擇值後一般都要轉成陣列再使用的,所以也可以在轉成陣列後,去除最後一個數組元素。