
This tutorial helps to add or remove textbox dynamically using jQuery and PHP. It also describes how to read the values of dynamically created textboxes and save them to the database.
Run this CREATE statement while setting up this example in your local environment.
CREATE TABLE `item` ( `id` int(11) NOT NULL, `item_name` varchar(255) NOT NULL, `item_price` double NOT NULL );
Save this code as input.php. This file will be loaded later using jQuery to append textbox HTML code to the target location.
<DIV class="product-item float-clear" style="clear:both;"> <DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV> <DIV class="float-left"><input type="text" name="item_name[]" /></DIV> <DIV class="float-left"><input type="text" name="item_price[]" /></DIV> </DIV>
The textbox markup will be added dynamically by using jQuery append() and load(). The code is,
function addMore() { $("<DIV>").load("input.php", function() { $("#product").append($(this).html()); }); }
We have the checkbox for each row dynamically added the text box for selecting rows to be removed from delete event. And script for removing checked items is,
function deleteRow() { $('DIV.product-item').each(function(index, item){ jQuery(':checkbox', this).each(function () { if ($(this).is(':checked')) { $(item).remove(); } }); }); }
This is, as usual, we have seen in several MySQL crud examples. The code is,
<?php if(!empty($_POST["save"])) { $conn = mysqli_connect("localhost","root","test", "blog_samples"); $itemCount = count($_POST["item_name"]); $itemValues=0; $query = "INSERT INTO item (item_name,item_price) VALUES "; $queryValue = ""; for($i=0;$i<$itemCount;$i++) { if(!empty($_POST["item_name"][$i]) || !empty($_POST["item_price"][$i])) { $itemValues++; if($queryValue!="") { $queryValue .= ","; } $queryValue .= "('" . $_POST["item_name"][$i] . "', '" . $_POST["item_price"][$i] . "')"; } } $sql = $query.$queryValue; if($itemValues!=0) { $result = mysqli_query($conn, $sql); if(!empty($result)) $message = "Added Successfully."; } } ?>
This screenshot shows the dynamically add input box using jQuery AJAX add more option. The checkboxes before the the dunamically added input field rows are used to bulk select the rows to delete.
Hi
Thanks for this post,it is really helpful.
I wanna add selecte menu php ajax in this page. What can i do ?
hi
Hi Sudhakar :-)
working excellenty,thanks.
Welcome Dasmahapatra, happy to hear :-)