Pass php checkbox variable to jQuery

Discussion in 'jQuery' started by ploppy, Nov 21, 2012.

  1. #1
    I am a new user to jQuery and am struggling trying to pass php variable to jQuery. I am using a checkbox in a while loop so because there can only be 1 id, I suffixed the id with $ticket, ie; id="check$ticket". I need to get this value in jQuery for processing. After hours of trying to figure it out, I throw myself at the experts to show me the way. I would be grateful if someone could point out my error or correct my code to grab this value. Thanks


    PHP Code

    while($row = mysql_fetch_array($result)) 
      {
    					
    	$ticket = $row['ticket_frm'];
    	$rowdate = date("d/m/Y",strtotime($row['date_frm']));
    	$id = $row['id_frm'];
    	$from = $row['from_frm'];
    	$subject = $row['subject_frm'];
    	$message = $row['message_frm'];
    					
    					
    	$myString = $myString . "<span><input id=\"check$ticket\" class=\"check\" type=\"checkbox\" name=\"delete[]\" value=\"$ticket\"></span>";
    	$myString = $myString . "<div class=\"msgTrue buttonMailTrue\" data-message=\"$message\" data-subject=\"$subject\" data-rowdate=\"%s\" data-from=\"%s\">";
    	$myString = $myString . "<img src=\"images/sml_new_mail_icon.gif\" class=\"mailIcon\" alt=\"\" />$subject";
    	$myString = $myString . "<div class=\"rowdate\">$rowdate</div><br />";
    	$myString = $myString . "<span class=\"mailFrom\">$from</span>";
    	$myString = $myString . "</div>";
    					
      }
            echo $myString; 
            echo '<p class="checked">'.'</p>';
    PHP:
    jQuery code

    $(function(){
    $("#check" + TICKET_NUMBER_HERE).click(function() {
       var isChecked = $(this).prop("checked");  // or $(this).prop("checked")
         if (isChecked) {
           $("p.checked").html("Checkbox is checked: <b>True</b>");
       } else {
           $("p.checked").html("Checkbox is checked: <b>False</b>");
    	 }
    	 });
    });
    Code (markup):

     
    ploppy, Nov 21, 2012 IP
  2. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #2
    1) $myString = $myString . "... when $myString hasn't been defined yet will throw an error.

    2) $myString .= "... is a lot neater.

    3) PHP code runs and generates the page sent to the browser. The user hasn't checked anything yet, because nothing has been sent to the browser yet.

    THEN the code is sent to the browser. The user checks boxes, jQuery runs. PHP has finished and the only way to talk to it again is with AJAX.

    If I'm reading you wrong, and you merely want the id of the checkbox to be "check".$ticket, just write the checkboxes with PHP:

    echo '<input type="checkbox" name="checkgroup" id="check'.$ticket.'"/>';
     
    Rukbat, Nov 22, 2012 IP