How to select checkbox on row click
Moderator: General Moderators
How to select checkbox on row click
Say you have a table with 5 columns per row and a checkbox in the first column. How do you write a script that checks the checbox when the user clicks anywhere in the row?
I can't figure this out for the life of me.
Thanks.
I can't figure this out for the life of me.
Thanks.
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Code: Select all
<script language="javascript">
function checkChecked( obj ) {
if (!obj.formname.checkboxname.checked) {
obj.formname.checkboxname.checked = true;
}
}
//-->
</script>
<form name="formname" id="formname">
<input type="checkbox" name="checkboxname" />This is a checkbox
<input type="image" src="images/mypic.jpg" onClick="checkChecked(this);" />
</form>
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
I can't get it to work. Here is my code:
Code: Select all
<script language="javascript">
function checkChecked( obj ) {
if (!obj.form1.checkbox1.checked) {
obj.form1.checkbox1.checked = true;
}
}
</script>
<body>
<table width="200" border="1">
<tr onClick="checkChecked(this);">
<td><form id="form1" name="form1" method="post" action="">
<label>
<input type="checkbox" name="checkbox1" />
</label>
</form> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
I think that code doesn't work because Javascript doesn't pass by reference. Once you pass 'this', you're making a copy of the row. Consequently, when you change the 'checked' status, you're changing it on the copy, not the page.
Would it be possible to pass along the name/id of the checkbox rather than a reference to the row? That way you can cut your code down to:
Would it be possible to pass along the name/id of the checkbox rather than a reference to the row? That way you can cut your code down to:
Code: Select all
function checkChecked(obj)
{
document.getElementByName(obj).checked = (document.getElementByName(obj).checked) ? false : true;
}Real programmers don't comment their code. If it was hard to write, it should be hard to understand.