I use this working code to add dynamically a row to a table with id "tableGenre" in the index.html file.
file -> script.js
$( document ).ready(function() {
var scntDiv = $('#tableGenre');
var i = $('#tableGenre tr').size() + 1;
$('#addLine').on('click', function() {
$('<tr><td>'+(i-1)+'</td><td><select name="genre[]" id="genre'+(i-1)+'"></select></td><td><a href="#" id="delLine" class="btn btn-xs red" ><i class="icon-remove"></i></a></td></tr>').appendTo(scntDiv);
alert(i);
i++;
return false;
});
});
I would like to be able to add a select box populated by mysql data in the same row inserted dynamically.
Each time the user presses the button "AddLine" should display a new row with a select box containing the list of options taken from the mysql database through the file "buildGenre.php". However, the new line is created, but the select box remains empty
I tried so but without success
file -> script.js (new)
$( document ).ready(function() {
var scntDiv = $('#tableGenre');
var i = $('#tableGenre tr').size() + 1;
$('#addLine').on('click', function() {
$('<tr><td>'+(i-1)+'</td><td><select name="genre[]" id="genre'+(i-1)+'"></select></td><td><a href="#" id="delLine" class="btn btn-xs red" ><i class="icon-remove"></i></a></td></tr>').appendTo(scntDiv);
alert(i);
// If element id "genre1" exist
if($("#genre"+(i-1)).length != 0) {
//alert("#genre"+(i-1)+" exist");
// i populate select box options with mysql data
$.ajax({
type: "GET",
url: "buildGenre.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#genre"+(i-1)).html(response);
alert(response);
}
});
}
i++;
return false;
});
});
file -> buildGenre.php
$listGenri = '';
$sql = "SELECT * FROM tbl_genre";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0){
$listGenri .='';
while($row = mysql_fetch_assoc($result)) {
extract($row);
$listGenri .= '<option value="'.$genre_id.'">'.$genre_name.'</option>';
}
}
echo $listGenri;
file -> index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<input name="btnAdd" type="button" id="addLine" value=" New Line " >
<table id="tableGenre" border="1">
<thead>
<tr>
<th>N.</th>
<th>Genre</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
Thanks in advance!