JavaScript操作checkbox的方式

JavaScript操作checkbox的方式和操作radio的方式相似,都是利用元素项的checked属性来完成。先获取checkbox元素集合,遍历集合,对集合中的每一项做操作。

 

<body>
	<p>
	<label for="hobby">Hobby:  
	<input type="checkbox" name="hobby" value="reading" />reading  
	<input type="checkbox" name="hobby" value="climbing" />climbing  
	<input type="button" value="Get Value" onclick="getValue()" />
	</label>
	</p>
</body>

 

 

function getValue(){
	var hobbies = document.getElementsByName("hobby");
	var value;
	for (i=0; i<hobbies.length; i++){
		if (hobbies[i].checked){
			if (!value){
				value = hobbies[i].value;
			} else {
				value += "," + hobbies[i].value;
			}
		}
	}
	
	alert(value == undefined ? '' : value);
}

 

javascript 中 select 下拉框

 

<select id="test">
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>
 
 1 拿到select对象: var  myselect=document.getElementById("test");

 2 拿到选中项的索引:var index=myselect.selectedIndex ;             // selectedIndex代表的是你所选中项的index

 3 拿到选中项options的value:  myselect.options[index].value;

 4 拿到选中项options的text:  myselect.options[index].text;

 

posted @ 2020-12-12 13:02  emanlee  阅读(762)  评论(0编辑  收藏  举报