Archive

Archive for the ‘JavaScript’ Category

Select All / Unselect All กับ checkbox (โดยใช้ javascript)

ธันวาคม 3rd, 2008

เป็นตัวอย่างโค้ดในการคลิกเพื่อเลือก checkbox ทั้งหมด และ คลิกเพื่อไม่แสดงทั้งหมด

<html>
<head>
  <title>Select-Unselect</title>
 
  <script language=“javascript”>
var flag = true;
function handler()
{
var myCheckboxAsPHPArr = document.myForm['myCheckbox[]‘];
 
if( myCheckboxAsPHPArr )
{
for(i=0; i<myCheckboxAsPHPArr.length; i++)
{
myCheckboxAsPHPArr[i].checked = flag;
}
flag = !flag;
 
if(flag)
{
document.myForm.myBtn.value = “Select All”;
}
else
{
document.myForm.myBtn.value = “Unselect All”;
}
}
}
  </script>
</head>
 
<body>
 
   <form method=“post” name=“myForm” action=“doPost.php”>
<input type=“checkbox” name=“myCheckbox[]“ />Checkbox 1<br/>
<input type=“checkbox” name=“myCheckbox[]“ />Checkbox 2<br/>
<input type=“checkbox” name=“myCheckbox[]“ />Checkbox 3<br/>
<input type=“checkbox” name=“myCheckbox[]“ />Checkbox 3<br/>
<input type=“button” name=“myBtn” value=“Select All” onclick=“handler();”/>
<input type=“submit” />
  </form>
 
</body>
</html>

JavaScript