Implementing a dynamic form with PHP,MySQL and AJAX
Hi,
I am trying to implement a dynamic form where in I can add the form elements basically two select boxes and a textarea. The select box is a chained one which is populated from a mysql database. The first row of my form is predefined and is working properly as expected. The first select data is sent to a php file for processing through AJAX and the list is retrieved.
But when i create the form elements dynamically, I am not able to perform this operation. Here is my code,
The form page
Code:
<tbody>
<tr>
<td><input type="checkbox" required="required" name="chk[]" /></td>
<td>
<label for="drop_1">Product Type</label>
<select name="drop_1[]" id="drop_1">
<option value="" selected="selected" disabled="disabled">Select a Category</option>
<?php getTierOne();?>
</select>
</td>
<td>
<span id="wait_1" style="display: none;">
<img alt="Please Wait" src="images/ajax-loader.gif"/>
</span>
</td>
<?php
echo "<input type='hidden' name='userid' value=$user_id />";
?>
<td><span id="result_1" style="display: none;"></span></td>
<td><label for="comment">Comments</label><textarea id="comment" name="comment" rows="5" cols="8"></textarea></td>
</tr>
</tbody>
AJAX
Code:
$(document).ready(function() {
$('#wait_1').hide();
$('#drop_1').change(function(){
$('#wait_1').show();
$('#result_1').hide();
$.get("dynamic.php", {
func: "drop_1",
drop_var: $('#drop_1').val()
}, function(response){
$('#result_1').fadeOut();
setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response) {
$('#wait_1').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
Dynamic field creation
Code:
var i = $('#dataTable tr').size() + 1;
$(function () {
var scntDiv = $('#dataTable');
$("#addScnt").click(function (e) {
$('<tr><td><input type="checkbox" required="required" name="chk[]" /></td><td><label for="drop_1_' + i + '">Product Type</label><select name="drop_1[]" id="drop_1_' + i + '"><option value="" selected="selected" disabled="disabled">Select a Category</option><option value="abcd">abcd</option><option value="efgh">efgh</option></select></td><td><span id="wait_1_' + i + '" style="display: none;"> <img alt="Please Wait" src="images/ajax-loader.gif"/></span></td><td><span id="result_1_' + i + '" style="display: none;"></span></td><td><label for="comment_' + i + '">Comments</label><textarea id="comment_' + i + '" name="comment[]" rows="5" cols="8"></textarea></td></tr>').appendTo(scntDiv);
i++;
return false;
});
});
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all products.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Can some one help me on this?