Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Select and deselect all checkboxes

Status
Not open for further replies.

chrismassey

Programmer
Aug 24, 2007
264
GB
I have javascript which I have incorporated into a PHP script which allows me to select all the checkboxes within a group by checking the 'check all' checkbox. The script is as follows...

Javascript:
Code:
<!--

function check_all(field, value) {
for (var i=0;i<document.forms[1].elements[field].length;i++) {
if(value == 1) {
document.forms[1].elements[field][i].checked = true
} else {
document.forms[1].elements[field][i].checked = false
}
}
}

// End -->

HTML Form:
Code:
<input type="checkbox" name="checkall" value="" onClick="check_all('checkbox[]',1)">

<input type="checkbox" name="checkbox[]" value="$file">
<input type="checkbox" name="checkbox[]" value="$file">
<input type="checkbox" name="checkbox[]" value="$file">

To deselect all checkboxes I must set the value to e.g. 2 so...

onClick="check_all('checkbox[]',2)"

However this means that I must have 2 checkboxes, 1 for selecting all and another for unselecting all. I would like this to be done within 1 checkbox.

I also have another script which does exactly what I want, however due to PHP my checkbox names must be followed by [] (array) to be able to pick up the data, and the javascript fails if I do this in the javascript below...

Code:
<!-- Begin
function Check(chk)
{
if(document.form.checkall.checked==true){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}else{

for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
}

// End -->

<input type="checkbox" name="checkall" value="" onClick="Check(document.form.check)">

Therefore i tried to incorporate this line in the former script...

if(document.form.checkall.checked==true){

however it hasn't worked. Can someone please help me in trying to adapt the 1st script to suit my needs. Thanks alot,

Chris
 

It's this simple:

Code:
<script type="text/javascript">

function check_all(group, action)
{
 for (var i=0; i<group.length; i++)
  group[i].checked = action;
}

</script>

<form>
<input type="checkbox" name="checkall" value="" onClick="check_all( this.form['checkbox[]'], this.checked )">

<input type="checkbox" name="checkbox[]" value="$file">
<input type="checkbox" name="checkbox[]" value="$file">
<input type="checkbox" name="checkbox[]" value="$file">
</form>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top