tags:

views:

208

answers:

4

Hi, I am making a page where the user can set there own settings. I need a loop to check the checkbox when the row is true and to be unchecked when its not. How would I go about this? in php/javascript.

Thanks

echo "<form method=\"post\">";

echo "<table>
<tr>
  <td>1</td>
   <td><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\"></td>
</tr>

<tr>
     <td>2</td>
     <td><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\"></td>
</tr>


</table>"; 
echo"<input name=\"update\" type=\"submit\" id=\"update\" value=\"Update\" method\"post\">";
echo "</form>";
A: 

Suppose you get a value from row and then while iterating do:

<input type="checkbox" <? if ($value==true) echo "checked=checked"; ?> />

PS. I just hope you are not expecting us to wrote here the entire whole code for you, right?

Artem Barger
Should be checked="checked" or nothing, true/false isn't valid HTML.
mgroves
No am not, just to get the idea of how to do it :)
Elliott
A: 

In your loop, add this:

 echo "<input type=\"checkbox\" ";
 if ( $value_which_should_be_true ) { echo "checked=\"checked\""; }
 echo "/>";

This uses the checked HTML attribute for checkboxes, which specifies the default state.

Lucas Jones
as stated above, this should be checked="checked"
KOGI
D'oh! I'm used to HTML's plain "checked" and guessed. Tah.
Lucas Jones
+1  A: 
while($row = mysql_fetch_assoc($rs))
{
    // some code...

    $checked = '';
    if($row['setting_1'] === TRUE)
    {
          $checked = 'checked="checked"';
    }

    echo '<input type="checkbox" name="setting_1" value="value_1" '.$checked.' />';

    // some code...

}
andyk
Thanks alot :) works great
Elliott
One more thing how can I add a loop to check the row? I have these stored in an array like $settings[0]. can I do something like for i = 1 to 5 etc ? Thanks
Elliott
edit: so I can use if settings[i] == true ......
Elliott
Just thought this wouldnt work. Never Mind, Thanks
Elliott
do you store all of the settings in one field ? if not, what does it (the table) look like ? It might be better if you could post that as a new question, to keep things clean and tidy. (eg. one question for one specific problem)
andyk
I just wanted a different way to do the if check...but then the $checked would also have to be changed for each checkbox. Different fields
Elliott
A: 

The checked attribute takes "checked" (see here), so I'd do something like:

<input type="checkbox" <? if ($value == true) echo 'checked="checked"'; ?> />

Alternatively, you can do something like:

if ($value == true) { $checked = 'checked="checked"' };
echo '<input type="checked".$checked.' />;
spiffyman