[英]check and uncheck boxes in javascript
我有一個腳本來檢查和檢查表單中的所有框,我的問題是我只希望它只影響我的復選框,但它也影響我的單選按鈕。
這是我的javascript
<script>
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
這是我的HTML
<form id ="frm1">
<input type="checkbox" name="chk1">
<input type="radio" name="chk1">
<input type="checkbox" name="chk2">
<input type='checkbox' name='checkall' onclick='checkedAll(frm1);'>
</form>
我想知道是否有辦法只檢查復選框而不是單選按鈕。
for (var i =0; i < aa.elements.length; i++)
{
if (aa.elements[i].type == "checkbox") {
aa.elements[i].checked = checked;
}
}
您可以遍歷表單元素並檢查“type”屬性。 或者,您可以使用jQuery之類的javascript庫,這樣可以更輕松地選擇特定類型的元素。
var elLength = document.MyForm.elements.length;
for (i=0; i<elLength; i++)
{
var type = MyForm.elements[i].type;
if (type=="checkbox" && MyForm.elements[i].checked){
alert("Form element in position " + i + " is of type checkbox and is checked.");
}
else if (type=="checkbox") {
alert("Form element in position " + i + " is of type checkbox and is not checked.");
}
else {
}
}
在jQuery中它將是:
$("input[type='checkbox']).each(function(chk) {
chk.checked = !chk.checked;
});
你可以使用jquery 。 在編輯器中使用下面的html代碼。 它工作正常!
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.js"> </script>
</head>
<form id="myform">
<input type="checkbox" />chk1
<input type="checkbox" />chk2<br/>
<input type="radio" />radio1<br/>
<a style="cursor:pointer" onclick="ch()">check/uncheck</a>
</form>
</body></html>
和這個腳本:
<script>
function ch(){
$("form#myform input[type='checkbox']").each(function(chk) {
this.checked = !this.checked;
});
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.