Page 1 of 1

Checkboxes in JavaScript and PHP

Posted: Sun Nov 27, 2005 9:32 am
by mur
Hi all,

I am having a problem with using javascript and php in the same project. I have simplified my code to make my problem easier to understand. Basically my probelm is: I have a form in HTML with a series of check boxes, that are manipulated in javascript. I do this by creating javascript funtions for the checkboxes, and calling them using "onClick=(apress(document.form1.boxes)" in my check box tag. This works fine, until I want to send these off to my PHP script in the $_POST array. I figured out how to get the values in the PHP by adding "[]" after name of each checkbox, but once I do this I am unable to use the javascript functions even when I change it to "onClick=(apress(document.form1.boxes[])"


My HTML and JavaScript:

Code: Select all

<html>
<form name="form1" method="post" action="mailer.php">
  <p>
    <input type="checkbox" name="boxes[]" value="a" onClick="apress(document.form1.boxes[])">
    a
  </p>
  <p>    <input type="checkbox" name="boxes[]" value="b"> 
  b
</p>
  <p>
    <input type="submit" name="Submit" value="Submit">
</p>
</form>
</html>

<script language="javascript">


function apress(field) {
	if(field[0].checked == true) {
		field[1].checked = false;
		alert();
	}
}



</script>
my PHP:

Code: Select all

<?php
$checkboxes = $_POST['boxes'];
	foreach($checkboxes as $box) {
		$message = $message . $box . "\n";
	}
	echo $message;
?>
Thanks for reading, and please let me know if you can help,
Mur

Posted: Sun Nov 27, 2005 1:24 pm
by nigma
To be honest, I don't know javascript quite well enough to tell you what you're doing wrong. However, here's one way to accomplish what you want.

Code: Select all

<form name="checkBoxForm" method="post" action="mailer.php">
<input type="checkbox" id="boxA" name="boxes[]" value="a" onclick="apress()" /> A
<input type="checkbox" id="boxB" name="boxes[]" value="b" />B
<input type="submit" />
</form>

Code: Select all

function apress() {
  boxA = document.getElementById("boxA");
  boxB = document.getElementById("boxB");
  if (boxA.checked) 
    boxB.checked = false;
    alert();
  }
}

Sorta

Posted: Sun Nov 27, 2005 2:10 pm
by mur
Like I said, I just simplified the code to show my problem. In realiity i have at least 40 checkboxes that all influence eachother based on how they are checked. And all of their statuses need to be mailed, so that seems like a last resort. I'm sure there is a way to do this. Thanks for posting tho.

Here we go

Posted: Sun Nov 27, 2005 3:43 pm
by mur
ok i got it working for anyone whose interested the problem was as i suspected the brackets [] were interfereing with the javascript the trick is to escape the brackets using

Code: Select all

apress(document.form1['boxes[]']);
instead of

Code: Select all

apress(document.form1.boxes[]);
Ok thanks anyways.
Mur