making a checkbox sticky

Discussion in 'PHP' started by rojojat, Nov 1, 2009.

  1. #1
    Hi,
    I created a form with some checkboxes. When a user checks the box and submits, the form is redisplayed with the results but the check is removed. I have been able to make the text entries stick but not the checkbox after submitting. How would I do this?
    thanks.
     
    rojojat, Nov 1, 2009 IP
  2. DansTuts

    DansTuts Guest

    Messages:
    923
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hey. It's quite simple but involves a little logic:

    <?php 
    
    // Coded by Daniel Clarke (DanMakes) 
    
    function checkbox($name,$value) { 
    	
    	// Get the value of the form and then if it's been checked. 
    	if ($_GET[$name] == $value) { 
    		// if it has return the HTMl for a checked checkbox.
    		return 'checked="checked"'; 
    	} 
    }
    
    ?>
    
    <input name="food" type="checkbox" <?php checkbox("food","ham") ?> id="checkbox" value="ham" />
    PHP:
    So use that function and then inside of the checkbox code type <?php checkbox("CHECKBOXNAME","CHECKEDVALUE") ?>. Hope that makes sense
     
    DansTuts, Nov 1, 2009 IP
  3. emed

    emed Peon

    Messages:
    70
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I use this function:
    function checkbox($var){
    	if($var)
    		return 'checked="checked"';
    }
    Code (markup):
    then i call the funcion on the checkbox:
    <input type="checkbox" name="boxName" value="1" <?=checkbox($_POST['boxName'])?> />
    Code (markup):
    or directly without a function:
    <input type="checkbox" name="boxName" value="1" <?=(($_POST['boxName']=='1')?'checked="checked"':'')?> />
    Code (markup):
     
    emed, Nov 1, 2009 IP
  4. DansTuts

    DansTuts Guest

    Messages:
    923
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #4
    That works on most checkboxs - but it won't work if any JS is used. :)
     
    DansTuts, Nov 1, 2009 IP
  5. rojojat

    rojojat Peon

    Messages:
    43
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thank You friends
     
    rojojat, Nov 1, 2009 IP
  6. AlphaBillion

    AlphaBillion Peon

    Messages:
    24
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Very useful, thanks
     
    AlphaBillion, Nov 1, 2009 IP