Steven Steven - 6 months ago 19
jQuery Question

php if statement check for radio button inside jquery

I am using the code below to have an add button in html to add a new textbox and radio buttons to the page when I click the add button. The names of the textboxes added are an input name plus an added number (the number of clicks) to differentiate the input data into different variables when I want to use it for different queries. I use this input(input is numeric) with the radio buttons to determine if I should query a certain data above or below the specified number, based on which radio button is checked.

<input id="btnAdd" type="button" value="Add" />
<br />
<div id="TextBoxContainer">
</div>
<br />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var click_number = 0;
$("#btnAdd").bind("click", function () {
var input = $("<label>input &nbsp;<textarea rows='1' name='input_"+ click_number +"'><?php echo $_POST['input_"+ click_number +"']; ?></textarea></label>&nbsp;");
var above_below = $("<input type='radio' name='abovebelow_"+ click_number +"' id='above_"+ click_number +"' value='Above' <?php if(isset($_POST['abovebelow_"+ click_number +"']) && $_POST['abovebelow_"+ click_number +"'] == 'Above') echo \"checked='checked'\"; ?>><label for='above_"+ click_number +"'>Above</label><input type='radio' name='abovebelow_"+ click_number +"' id='below_"+ click_number +"' value='Below' <?php if(isset($_POST['abovebelow_"+ click_number +"']) && $_POST['abovebelow_"+ click_number +"'] == 'Below') echo \"checked='checked'\"; ?>><label for='below_"+ click_number +"'>Below</label><br/>&nbsp;");
hgcBio.appendTo('#TextBoxContainer');
above_below.appendTo('#TextBoxContainer');
click_number++;
});
</script>


Currently, the html works when not using it in jqeury, but when in this jquery format the radio buttons don't work. I have narrowed the error down to the php code that is in the above/below variable:

<?php if(isset($_POST['abovebelow_"+ click_number +"']) && $_POST['abovebelow_"+ click_number +"'] == 'Above') echo \"checked='checked'\"; ?>


because when I delete this part, I no longer get an error message. The error message is "Parse error: parse error, expecting `"identifier (T_STRING)"'" on that line. Since I have used php in other parts of the jQuery (the input variable), I'm guessing the problem is the if statement? Is there another way to use an if statement here? Or possible another way to do this?

Answer

Is it just simple like

<?php 
    if(isset($_POST['abovebelow_". click_number ."']) 
         && $_POST['abovebelow_". click_number ."'] == 'Above') 
        echo "\"checked='checked'\""; 
?>

(i.e. you forgot double qoutes before and after the printed string. Also the concatenation of string should be using . not + in php, as mentioned in comments)

Comments