Jump to content

Recommended Posts

Hi,

I'm trying to check a box in a form based on the $status variable read from a json file. If it's a 1 then the checkbox is checked, otherwise not.

If I check/uncheck it, then the $status is written back to the json file. It's a rather simple code but I just cannot get it right.

I appreciate any help.

TIA

 

<div class="field">
  <?php
  if ($status == 1){
  $checked = "checked";
  }
  echo '<input name="ck1" type="checkbox" value='.$status.' '.$checked.' >';
  ?>                     
  <label for="ck1">Active</label>
  <!-- <input name='ck1' type='checkbox' <? if $status : "checked" ?> value = "<?=$status ?>" /> -->
  </div>

 

Link to comment
https://forums.phpfreaks.com/topic/310285-ckbox-cked-based-on-var/
Share on other sites

The code could use some improvement but it should work. Have you done a View Source of the page to make sure the HTML being outputted is correct? Does "cannot get it right" mean anything more than just the checkbox remaining unchecked?

Modified a bit the code but still no avail...

<?php
   if ($status == 1){
   echo '<input name="ck1" type="checkbox" value='.$status.' checked >';
   }
   else {
   echo '<input name="ck1" type="checkbox" value='.$status.' >';
   }
?>

The html output is this...

<div class="field">
 <label for="ck1">Activa</label>
 <input name="ck1" type="checkbox" value=0 > 
</div>

 

What that html will do is return a 0 when the box is checked.  It returns nothing at all if it is not checked.  In fact the $_POST array will not have an element named 'ck1' in it unless the box is checked.

As for returning a different value, perhaps you should be using a pair of radio buttons instead of a checkbox.

Edited by ginerjm
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.