獲取input框中的值的三種方式
<input type="text" name="demo1" id="demo2" value="你好">
上面是一個input框,其中數據值是“你好”,如果要獲取其值有三種方式,其中兩種是JS方式,一種是JQuery的方式
// 方式一:
document.all.demo1.value; // 通過name獲取
document.all.demo2.value; // 通過id獲取
// 方式一推薦通過id獲取,因爲name可能會有重複值,比如option標籤或者input標籤的radio類型等
// 方式二:
document.getElementById("demo2").value;
// 方式三:
$("#demo2").val();
document.all的含義:
1.這個是用來獲取頁面內所有元素的一個集合。例如:document.all(0)表示頁面內第一個元素。
2.也可以用來判斷當前瀏覽器是不是IE
if(document.all){
alert("this is IE!");
}
判斷checkbox框是否被選中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>checkbox的案例</title>
<script type="text/javascript">
// 判斷checkbox是否有選中
function howManyChecked() {
// 獲取所有input框元素
var input = document.getElementsByTagName("input");
alert("獲取到"+input.length+"個input框");
// 循環獲取到的input框元素,判斷是否名字爲book
for (var i = 0; i < input.length; i++) {
if (input[i].name == "book" && input[i].type=="checkbox") {
if(input[i].checked==true) {
alert("這是選中框:"+input[i].value);
}
}
}
}
</script>
</head>
<body>
姓名:<input type="text" name="name" id="name" value="張三" /><br/>
年齡:<input type="text" name="age" id="age" value="15" /><br/>
讀書:
<input type="checkbox" name="book" value="語文" />語文
<input type="checkbox" name="book" value="數學" />數學
<input type="checkbox" name="book" value="英語" />英語
<input type="button" name="button" id="button"
value="查看有幾個checkbox被選中" onclick="howManyChecked()"/>
</body>
</html>
js中可以直接通過獲取元素,然後點屬性即可,但是需要確認一下屬性對應的值是什麼,比如checked的值就是true或false