Jump to content

Checkbox name arrays like namehere[] echoing back selected boxes checking all


OldWest

Recommended Posts

I am simply trying to keep a check box checked once selected. What I have works, but not correctly.

 

Because I am calling each array element in my checkbox like

 

 name="checkbox[]"

 

And I am using this as the input return the check:

 

<input type="checkbox" name="checkbox[]" value="checkOneValue" <?php if(isset($_POST['checkbox'])) echo "checked"; ?> />

 

I have 5 checkboxes that use the same code! And as I said it works, but returns ALL checkboxes as selected when submitted.

 

I only want the actual selected boxes to remained checked.

 

Any insight on a work around? The problem is I cannot solve how to identify unique array values as they are all named the same... Maybe I am not thinking right on all of this.

 

Here is my full source code:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Checkbox Echoing Test</title>
</head>
<body>
<form name="" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  One
  <input type="checkbox" name="checkbox[]" value="checkOneValue" <?php if(isset($_POST['checkbox'])) echo "checked"; ?> />
  <br />
  Two
  <input type="checkbox" name="checkbox[]" value="checkTwoValue" <?php if(isset($_POST['checkbox'])) echo "checked"; ?> />
  <br />
  Three
  <input type="checkbox" name="checkbox[]" value="checkThreeValue" <?php if(isset($_POST['checkbox'])) echo "checked"; ?> />
  <br />
  Four
  <input type="checkbox" name="checkbox[]" value="checkFourValue" <?php if(isset($_POST['checkbox'])) echo "checked"; ?> />
  <br />
  Five
  <input type="checkbox" name="checkbox[]" value="checkFiveValue" <?php if(isset($_POST['checkbox'])) echo "checked"; ?> />
  <br />
  <input type="submit" name="submit" value="Echo Checkbox Data!" />
</form>
<?php



if (isset($_POST['checkbox']) && (isset($_POST['submit']))) { 

$checkbox = $_POST['checkbox'];

	foreach ($checkbox as $checkboxValue) {

		var_dump($checkboxValue);

			if (!empty($checkboxValue)) {
					echo "<br />$checkboxValue is checked";
				}
			}	
		}; // End of foreach loop

		if (!isset($_POST['checkbox']) && (isset($_POST['submit']))) {
					echo "<br />No checkboxes were selected!";
};

?>
</body>
</html>

 

Link to comment
Share on other sites

What you're doing is checking whether any value in the $_POST['checkbox'] array in present, and if so echoing the "selected" in all the fields. You need to compare the values of each checkbox to what's in the array, then only echo the "selected" if that individual value is present. like so:

<input type="checkbox" name="checkbox[]" value="checkOneValue" 
<?php echo ( is_array($_POST['checkbox']) && in_array('checkOneValue', $_POST['checkbox']) ) ? ' checked="checked"' : ''; ?> />

 

P.S. In case you aren't familiar with it, the ? : syntax uses the ternary operator.

Link to comment
Share on other sites

Yes, or give them indexes.  It all depends:

 

<input type="checkbox" name="checkbox[1]" value="checkOneValue" <?php if(isset($_POST['checkbox'][1])) echo "checked"; ?> />
<input type="checkbox" name="checkbox[2]" value="checkTwoValue" <?php if(isset($_POST['checkbox'][2])) echo "checked"; ?> />

Link to comment
Share on other sites

Yes, or give them indexes.  It all depends:

 

<input type="checkbox" name="checkbox[1]" value="checkOneValue" <?php if(isset($_POST['checkbox'][1])) echo "checked"; ?> />
<input type="checkbox" name="checkbox[2]" value="checkTwoValue" <?php if(isset($_POST['checkbox'][2])) echo "checked"; ?> />

 

Nice profile pic. We've almost got the whole family on here now. Just need the Dinosaur and the others..

 

I like your approach on the number system, just not sure if that will work with my current code setup, so I will see what I can do. Thanks.

Link to comment
Share on other sites

What you're doing is checking whether any value in the $_POST['checkbox'] array in present, and if so echoing the "selected" in all the fields. You need to compare the values of each checkbox to what's in the array, then only echo the "selected" if that individual value is present. like so:

<input type="checkbox" name="checkbox[]" value="checkOneValue" 
<?php echo ( is_array($_POST['checkbox']) && in_array('checkOneValue', $_POST['checkbox']) ) ? ' checked="checked"' : ''; ?> />

 

Nice. I was messing around with the ternary a few days ago. Looks like I can toy with it now to make some use. Thanks for the insight. I like the ternary style.

 

P.S. In case you aren't familiar with it, the ? : syntax uses the ternary operator.

Link to comment
Share on other sites

Pikachu2000,

 

I am still unable to debug this... I am starting to think there might not be much purpose to keep checkboxes checked on a php self form submission..

 

In a real life scenario I think passing the values from page to page would make much more sense in a multi page form or something like that..

 

And I THINK :shrug: using a $_SESSION might work better for this... Anyhow looks like it's back to the drawing board to get this to work on a multi page form..

 

Need to rethink this thing now... Any tips for a better or smarter direction are welcome

Link to comment
Share on other sites

Not keeping the checkboxes checked would kind of depend on the purpose of the checkbox. For example, most sites don't keep a "ckeck this box if you agree with out TOS" checked so you actually have to take action each time you submit the form, and can't argue that the box was already checked, and you didn't understand, etc.

 

Keeping them checked really isn't a complicated process in and of itself, but it can become one if you try to overthink it. It's truly no different than making any other form field 'sticky', you just need to plan it out a bit.

Link to comment
Share on other sites

Not keeping the checkboxes checked would kind of depend on the purpose of the checkbox. For example, most sites don't keep a "ckeck this box if you agree with out TOS" checked so you actually have to take action each time you submit the form, and can't argue that the box was already checked, and you didn't understand, etc.

 

Keeping them checked really isn't a complicated process in and of itself, but it can become one if you try to overthink it. It's truly no different than making any other form field 'sticky', you just need to plan it out a bit.

 

Thanks and makes sense. I'll get it solved for my learning needs and post my code up when done.. Yeah no doubt its so easy to overthink this "simple" stuff.

Link to comment
Share on other sites

I've got about 4 more hours down the pipe on this, and I am starting to think there is a bug with php and checkbox values being set...

 

Just for kicks, I added some input fields and had them echoed $_POST back data stored OK.. Tried the same method with the checkboxes no dice.

 

 

 

 

Link to comment
Share on other sites

Checkbox values are only sent to PHP if they are checked.

 

Can you post your current code?

 

Ken

 

Hi Ken,

I just posted what I have.. Ive been through about 20 iterations and variations of the above. The above IS throwing errors! I just CANNOT for the life of me see how non-static array values can be used in this way..

 

I can see how I could do this all if all of the html and name="" values were static.. But using the array like I am, I am starting to think it is just not possible or PHP does not support this.

Link to comment
Share on other sites

Hi Ken I'm sorry my code did not go up..

 

Here is a WORKING static version I am testing with (and below it is the ARRAY version which I think php is buggy with):

 

<html>
<head>
<title>Checkboxes</title>
<?PHP
$ch1 = 'unchecked';
$ch2 = 'unchecked';
$ch3 = 'unchecked';
$ch4 = 'unchecked';
$ch5 = 'unchecked';

if (isset($_POST['Submit1'])) {

if (isset($_POST['ch1'])) {
	$ch1 = $_POST['ch1'];

	if ($ch1 == 'net') {
		$ch1 = 'checked';
	}
}

if (isset($_POST['ch2'])) {
	$ch2 = $_POST['ch2'];

	if ($ch2 == 'word') {
		$ch2 = 'checked';
	}
}

if (isset($_POST['ch3'])) {
	$ch3 = $_POST['ch3'];

	if ($ch3 == 'excel') {
		$ch3 = 'checked';
	}
}

if (isset($_POST['ch4'])) {
	$ch4 = $_POST['ch4'];

	if ($ch4 == 'web') {
		$ch4 = 'checked';
	}
}

if (isset($_POST['ch5'])) {
	$ch5 = $_POST['ch5'];

	if ($ch5 == 'php') {
		$ch5 = 'checked';
	}
}
}

?>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="<?php echo $_SERVER['PHP_SELF']; ?>">
  <Input type = 'Checkbox' Name ='ch1' value ="net" <?PHP echo $ch1; ?>>
  Value 1
  <P>
    <Input type = 'Checkbox' Name ='ch2' value="word" <?PHP echo $ch2; ?>>
    Value 2
  <P>
    <Input type = 'Checkbox' Name ='ch3' value="excel" <?PHP echo $ch3; ?>>
    Value 3
  <P>
    <Input type = 'Checkbox' Name ='ch4' value="web" <?PHP echo $ch4; ?>>
    Value 4
  <P>
    <Input type = 'Checkbox' Name ='ch5' value="php" <?PHP echo $ch5; ?>>
    Value 5
  <P>
    <INPUT TYPE = "Submit" Name = "Submit1"  VALUE = "Choose your books">
</FORM>
</body>
</html>

 

Array version (which is throwing errors now because Im on the 23rd iteration and variation of code to get this working!)

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Array Populate w/ Database</title>
</head>
<body>
<h1>Array *Checkbox Populate w/ Database</h1>
<?php require('db_cxn.php'); ?>
<?php

$cxn = mysqli_connect($host,$user,$pass,$db) or die("Could not connect to the server.");

$query = "SELECT DISTINCT cat FROM product ORDER BY cat";

$results = mysqli_query($cxn,$query) or die("Could not execute query.");

?>
<p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <input type="submit" name="runQueryCheckboxes" value="Run Query for Category Radio Options" />
</form>
</p>
<ul>
  <?php

$cat = 'unchecked';

if(isset($_POST['runQueryCheckboxes'])) {

if (isset($_POST['$cat'])) {

	$chk1 = $_POST['$cat'];

		if ($chk1 == 'CakePHP') {
			$chk1 = 'checked';
	}
}	
};

if(isset($_POST['runQueryCheckboxes'])) {

while($row = mysqli_fetch_array($results))
	{ extract($row);
		echo "<li><input type='checkbox' name='selection[$cat]' id='$cat' value='$cat' checked='$chk1'  />
					<label for='$cat'>$cat</label></li>";
					var_dump('');
	}
};

?>
</ul>
</body>
</html>

 

 

Link to comment
Share on other sites

Here's a quick script I just wrote which does what you want.

<?php
if (isset($_POST['submit'])) {
echo '<pre>' . print_r($_POST,true) . '</pre>';
}
?>
<html>
<head>
	<title>Checkbox test</title>
</head>
<body>
	<form action="" method="post">
		<?php
			$tmp = array();
			for($i=0;$i<10;++$i) {
				$chk = (isset($_POST['checkbox']) && in_array("checkbox$i",$_POST['checkbox']))?'checked':'';
				$tmp[] = '<label for="checkbox' . $i . '">Checkbox ' . $i . '</label>';
				$tmp[] = '<input type="checkbox" name="checkbox[]" value="checkbox' . $i . '" ' . $chk . '><br>';
			}
			echo implode("\n",$tmp) . "<br>\n";
		?>
		<input type="submit" name="submit" value="send checks">
	</form>
</body>
</html>

 

To see it in actions go to http://rbnsn.com/phpfreaks/checkbox_test.php

 

Ken

Link to comment
Share on other sites

Here is my table dump so you can see where I am getting my CakePHP from:

 

 

-- phpMyAdmin SQL Dump

-- version 3.2.0.1

-- http://www.phpmyadmin.net

--

-- Host: localhost

-- Generation Time: Oct 28, 2010 at 02:03 AM

-- Server version: 5.1.36

-- PHP Version: 5.3.0

 

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

 

--

-- Database: `dummies`

--

 

-- --------------------------------------------------------

 

--

-- Table structure for table `product`

--

 

CREATE TABLE IF NOT EXISTS `product` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `product` varchar(100) NOT NULL,

  `cat` varchar(100) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

 

--

-- Dumping data for table `product`

--

 

INSERT INTO `product` (`id`, `product`, `cat`) VALUES

(1, 'Programming Book for CakePHP', 'CakePHP'),

(2, 'jQuery Programming for Dummies', 'jQuery'),

(3, 'Jason''s Book', 'General'),

(4, 'The Story of PHP & MySQL', 'MySQL'),

(5, '', 'Ruby'),

(6, '', 'Python');

 

Link to comment
Share on other sites

Here's a quick script I just wrote which does what you want.

<?php
if (isset($_POST['submit'])) {
echo '<pre>' . print_r($_POST,true) . '</pre>';
}
?>...

To see it in actions go to http://rbnsn.com/phpfreaks/checkbox_test.php

Ken
[/quote]

That's some mad skills! Well at least I know now I was not totally wasting my time on something that was impossible! Thank you for curing my madness!! I've got at least 10 hours in trying to solve this.. Had some great tips along the way, but I think this closes the case..

I like how you echoed the Array out as well.. That certainly helps paint the picture as well..

Link to comment
Share on other sites

Ken,

 

That's some mad skills! Well at least I know now I was not totally wasting my time on something that was impossible! Thank you for curing my madness!! I've got at least 10 hours in trying to solve this.. Had some great tips along the way, but I think this closes the case..

 

I like how you echoed the Array out as well.. That certainly helps paint the picture as well..

Link to comment
Share on other sites

Well Im going back to re study arrays and for loops.. Trying to find out if I can nest a while loop inside a for loop (or if this even makes sense)... Need to get back to basics. I think this endeavor was a bit too steep a learnin curve.

 

Thanks for the help and tips.

Link to comment
Share on other sites

Ken,

 

I am messing around with your For loop code, and I am able to integrate it to the same degree as I have been... The select boxes won't stay checked.. But I have the print_r printing the selected array items after the submit which I think means something is being "held"... Now I just need to figure out how to get those checkboxes checked...

 

I don't want you to tell me the answer, but if you could tell me where to investigate in the code... I don't even know if I am using the forloop right with the limited (center) $row var I have in there, but it seems to work so :shrug:

 

Thanks for any guidance. I think I am close to being a step ahead of where I was 48 hours ago in using arrays.

 

Here is my code:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Arrays</title>
</head>
<body>
<?php require('db_cxn.php'); ?>
<?php
$cxn = mysqli_connect($host,$user,$pass,$db) or die("Could not connect to the server.");
$query = "SELECT DISTINCT cat FROM product ORDER BY cat";
$results = mysqli_query($cxn,$query) or die("Could not execute query.");
?>
<?php
if (isset($_POST['runForLoop'])) {
echo '<pre>' . print_r($_POST,true) . '</pre>';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <?php

			$tmp = array();
			for($i=0;$row = mysqli_fetch_array($results);++$i) {
				extract($row);
				$chk = (isset($_POST['checkbox']) && in_array("checkbox$i",$_POST['checkbox']))?'checked':'';
				$tmp[] = '<label for="checkbox' . $cat . '">Checkbox ' . $cat . '</label>';
				$tmp[] = '<input type="checkbox" name="checkbox[]" value="checkbox' . $cat . '" ' . $chk . '><br>';
			}
			echo implode("\n",$tmp) . "<br>\n";
			echo count($tmp); // counts all array elements
		?>
  <input type="submit" name="runForLoop" value="Run For Loop >>" />
</form>
</body>
</html>

 

Link to comment
Share on other sites

I got it working with my database driven array!!

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Arrays</title>
</head>
<body>
<?php require('db_cxn.php'); ?>
<?php
$cxn = mysqli_connect($host,$user,$pass,$db) or die("Could not connect to the server.");
$query = "SELECT DISTINCT cat FROM product ORDER BY cat";
$results = mysqli_query($cxn,$query) or die("Could not execute query.");
?>
<?php
if (isset($_POST['runForLoop'])) {
echo '<pre>' . print_r($_POST,true) . '</pre>';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <?php

			$tmp = array();
			for($i=0;$row = mysqli_fetch_array($results);++$i) {
				extract($row);
				$chk = (isset($_POST['checkbox']) && in_array("checkbox$i",$_POST['checkbox']))?'checked':'';
				$tmp[] = '<label for="checkbox' . $cat . '">' . $cat . '</label>';
				$tmp[] = '<input type="checkbox" name="checkbox[]" value="checkbox' . $i . '" ' . $chk . '><br>';
			}
			echo implode("\n",$tmp) . "<br>\n";
			echo count($tmp); // counts all array elements
		?>
  <input type="submit" name="runForLoop" value="Run For Loop >>" />
</form>
</body>
</html>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.