jquerty获取input,radio,checkbox,select标签的值

jquerty获取input,radio,checkbox,select标签的值

在使用jquert时,要先导入jquerty的文件

1.input的type="text"输入框
	<body>
		uname:<input type="text" id="name"/>
	</body>
	<script src="js/jquery-1.8.3.min.js"></script>
	<script>
		//获取input标签的值
		var uname=$("#name").val();
		//设置input标签的值
		$("#name").val("你好");
	</script>
2.input的type="radio"单选框

获取单选按钮的值是 input标签里面一定要设置value值并且一组radio的name属性的值要保持一致
input标签里的checked属性即默认选择

	<body>
		<input type="radio" name="sex" value="男"/><!--checked属性  设置默认选项-->
		<input type="radio" name="sex" value="女" checked/></body>
	<script src="js/jquery-1.8.3.min.js"></script>
	<script>
		//获取name='sex'的input被选中的值
		var sex=$("input[name='sex']:checked").attr("value"));
	</script>
3.input的type="checkbox"多选框
	<body>
		<input type="checkbox" name="habit" value="画画"/>画画
		<input type="checkbox" name="habit" value="唱歌"/>唱歌
		<input type="checkbox" name="habit" value="跳舞"/>跳舞
	</body>
	<script src="js/jquery-1.8.3.min.js"></script>
	<script>
		//获取name='habit'的input被选中的值,存到数组habits中
		var habits=[];
		$("input[name='habit']:checked").each(function(index,item){
			habits[habits.length]=item.value;
		})
		
		//全选
		$("input[name='habit']").each(function(){
			$(this).prop("checked","true");
		})

		//全部选
		$("input[name='habit']").each(function(){
			$(this).prop("checked","false");
		})
	</script>
4.select标签
	<body>
		<select>
			<option name="city">湖北</option>
			<!-- selected="true"  设置select默认的选项 -->
			<option name="city" selected="true">上海</option>
			<option name="city">长沙</option>
			<option name="city">深圳</option>
			<option name="city">北京</option>
		</select>
	</body>
	<script src="js/jquery-1.8.3.min.js"></script>
	<script>
		console.log($("select").find("option[name='city']:selected").text());
	</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章