Reputation: 47
I'm facing a problem with dynamically generated fields using JavaScript.
I have this code:
$goods="SELECT * FROM goods ORDER BY name";
$options = "";
$vys = mysqli_query($db, $goods);
while ($arr= mysqli_fetch_assoc($vys)) {
$options .= "<option value='".$arr['id_good']."'>".$arr['name']."</option>";
}
echo "
<script type=\"text/javascript\">
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = \"<select name=idg[]><?php echo $options; ?></select> \";
document.getElementById(divName).appendChild(newdiv);
}
</script>
<form method='post'>
<fieldset>
<div id='dynamicInput'><div>
<select name=idg[]>
$options
</select><br />
</div></div>
<input type='button' value='Add another select' onClick=\"addInput('dynamicInput'); \">
</fieldset>
</form>
First select is ok, but every other (generated) shows the list of options without the first item. I don't know why, but everytime i click the Add another select, it generates me new select with options, but the first item is missing (the first shown is the "second item in that ordered list").
Where is the mistake that when generated new select, the first item in ordered list is not shown, please?
Upvotes: 1
Views: 122
Reputation: 47
The right answer was a mistake when using
newdiv.innerHTML = \"<select name=idg[]><?php echo $options; ?></select> \";
instead of this, correct code:
newdiv.innerHTML = \"<select name=idg[]>$options</select> \";
Upvotes: 0
Reputation: 76636
You are trying to use <?php ?>
tags inside the echo
statement. They have no special meaning inside string context -- it's not required and will mess up the HTML markup.
newdiv.innerHTML = \"<select name=idg[]><?php echo $options; ?></select> \";
should be changed to:
newdiv.innerHTML = \"<select name=idg[]>$options</select> \";
The modified code would look like:
<script type=\"text/javascript\">
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = \"<select name=idg[]>$options</select> \";
document.getElementById(divName).appendChild(newdiv);
}
</script>
Upvotes: 1