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>