# This Source code in php would help you to create dynamic textboxes which would be just clone of already made . The limit is upto 12 textboxes but you can change that and all the values that user will input will be stored in the mysql database in json formate.
<!DOCTYPE html>
<html>
<head>
<!-- <style>
#textbox1, #textbox2 {
display: block;
float: left;
width: 100px;
}
</style>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var max_fields = 12; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var submit = $("#container2");
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append(' <div><input type="text" name="key[]" id="textbox1" style="margin-right:5em; margin-top:2em;"> <input type="text" name="value[]" id="textbox2"> <a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
</head>
<body>
<form name="user-data" id="usr" method="post" enctype="multipart/form-data">
<div class="input_fields_wrap">
<div>
<em style="margin-right:11em;">Text Box1</em>
<em>Text Box2</em>
</div>
<div>
<input type="text" name="key[]" id="textbox1" class="input" style="margin-right:5em">
<input type="text" name="value[]" class = "input" id="textbox2">
<button class="add_field_button">+</button>
</div>
</div>
<div class="container2" style="margin-top:2em; display:block;"><input type=submit
class="bt" onclick="GetTextValue()"
name="btSubmit" id=btSubmit value=Submit />
</div>
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$select = mysql_select_db("info",$conn);
if(isset($_POST['btSubmit'])){
$jsonArray = array();
$itemCount = count($_POST["key"]);
$array1 = $_POST["key"];
$array2 = $_POST["value"];
$jsonArray = array();
$jsonArray=array_combine($array1,$array2);
echo $json = json_encode($jsonArray);
$query = "INSERT INTO info (serial,data) VALUES (NULL,'".$json."');";
$sql = $query;
if($itemCount!=0) {
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
mysql_close();
}
?>
</body>
</html>
Comments
Post a Comment