I have successfully add & remove the dynamic input fields. However, I am facing a problem on inserting the input fields' values into my database. Any input on this would be appreciated. Thank you.
Input fields
<div id = "container">
<p class = "origin-box">
<label for = "Origin">From <span class = "box-number1">:</span></label>
<input type = "text" name = "Origin" value = "" id = "Origin"/>
<a class = "add-box" href = "#" name = "addBox"><img src = "Add Button.png" width = "35" height = "35" hspace = "20" vspace = "10" align = "middle"/></a>
</p>
<p class = "destination-box">
<label for = "Destination">To <span class = "box-number2">:</span></label>
<input type = "text" name = "Destination" value = "" id = "Destination"/>
</p>
</div>
JQuery for dynamically adding/removing input fields.
<script type="text/javascript">
jQuery(document).ready(function($){
var counter = 1;
var max_fields = 10;
$('.my-form .add-box').click(function(e){
e.preventDefault();
if (counter < max_fields){
counter++;
$('#container').append(
'<div><strong>Link #' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="fields[]' + '" type="text" placeholder = "From" /><a href = "#" class = "remove-box"><img src = "Remove Button.png" height = "35" width = "35" align = "middle"/></a></div><br />' );
}
});
$('.my-form').on('click', '.remove-box', function(e){
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().slideUp("fast","linear", function() {
e.preventDefault();
$(this).closest('div').remove(); //$(this) references the closest <div>
counter--;
});
return false;
});
});
</script>
After clicked on Submit button.
<p><input id = "btnSubmit" type = "submit" name= "submit" value = "Submit" /></p>
SQL statement for data insertion to database's tables.
if(isset($_POST['btnSubmit'])){
//create instance of database class
$db = new mysqldb();
$db->select_db();
//Check if user has actually added additional fields to prevent a php error
if ($_POST['fields']) {
//get last inserted userid
$inserted_user_id = $db->last_insert_id();
//Loop through added fields
foreach ( $_POST['fields'] as $key=>$value ) {
//Insert into transport table
$sql_transport = sprintf("INSERT INTO tbl_transport (Origin) VALUES ('%s')",
mysql_real_escape_string($value));
$result_transport = $db->query($sql_transport);
$inserted_transport_id = $db->last_insert_id();
//Insert into mainclaim table
$sql_mainclaim = sprintf("INSERT INTO tbl_mainclaim (transportID) VALUES ('%s')",
mysql_real_escape_string($inserted_transport_id));
$result_mainclaim = $db->query($sql_mainclaim);
}
} else {
//No additional fields added by user
}
//disconnect mysql connection
$db->kill();
}