Sometime we need to add or remove fields dynamically in a form.
In this article I'm explaining that how can we add or remove the fields using jQuery.
We just need to click on Add more button and a new field will be added. You also can remove that field.
In this article I also have written the code for inserting the data into MySql.
Here I'm giving an example of tags.
Like If we have requirement of add more tags. And we want to add tags as much as we want. You can do that easily by using this code.
You also can insert all the tags into the MySql database using PHP.
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<form method="post" action="submit.php">
<div class="wrapper">
<button id="add_more">Add More</button>
<div>
<input type="text" name="tags[]">
</div>
</div>
<input type="submit" name="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$( "#add_more" ).on( "click", function(e) { //on add input button click
e.preventDefault();
$(".wrapper").append('<div><input type="text" name="tags[]"/><a href="javascript:void(0);" class="remove_tag">Remove</a></div>'); //add input box
});
$(".wrapper").on('click', '.remove_tag', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
});
});
</script>
|
submit.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<?php
if($_POST['submit']){
<!--- Database Connection --->
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tags_db";// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
<!--- End Of Database Connection --->
$tags_array = $_REQUEST['tags'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
$sql = '';
foreach($tags_array as $tag){
$sql.= "INSERT INTO tags (tag_name)
VALUES ('".$tag."');";
}
// here we are doing batch insert or you can say we are inserting all the tags in one time.
if ($conn->multi_query($sql) === TRUE) {
echo "Tags inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
|