Page 1 of 1

How to select checkbox on row click

Posted: Wed Jul 26, 2006 1:11 am
by paultfh
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.

Posted: Wed Jul 26, 2006 2:02 am
by RobertGonzalez

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>

Posted: Wed Jul 26, 2006 2:16 am
by paultfh
I don't see how I incorporate that into a row

Posted: Wed Jul 26, 2006 3:07 am
by RobertGonzalez
The same way it is incorporated into an image... the onClick event. :wink:

Posted: Wed Jul 26, 2006 3:19 am
by paultfh
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>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>

Posted: Wed Jul 26, 2006 3:23 am
by RobertGonzalez
Let me check the code. It may be wonky.

Posted: Wed Jul 26, 2006 10:35 am
by pickle
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:

Code: Select all

function checkChecked(obj)
{
  document.getElementByName(obj).checked = (document.getElementByName(obj).checked) ? false : true;
}

Posted: Wed Jul 26, 2006 11:26 am
by Weirdan
because Javascript doesn't pass by reference.
objects in JS are always passed by ref.

Posted: Wed Jul 26, 2006 11:40 am
by pickle
.... I could have sworn they weren't. Thanks for the correction.