Add and Remove input textbox with Jquery, Javascript
Hello everyone, to continue the series of articles about Jquery and Javascript, in this article I introduce you to the small code about adding and removing form elements using Javascript, with specific example is input textbox.
On the same screen, you can add and remove elements including textboxes and checkboxes without reloading the page. By naming the element an array, the final result when the action post the PHP form will get the value of all selected elements.
Add and remove input textbox with Jquery, Javascript
1. Library
We only need Jquery and Bootstrap’s css (here we use bootstrap 3.3.6)
“https://code.jquery.com/jquery-3.5.1.min.js”
“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css”
2. HTML
Use tables to show the elements added and remove
// Code php in the download file
3. CSS
.container {
width: 500px;
margin: 0 auto;
}
.add_item{
float: right;
}
.btn_add_item{
margin-top: 10px;
}
4. PHP set default
// Data received from Database
// Default input element is 5
$data_program_names = [];
$number_input_default = 5;
5. Javacript
// Add event
$(‘.btn_add_item’).on(‘click’, function () {
// code in the download file…
});// Delete event
$(document).on(‘click’, ‘.btn_delete_item’, function (e) {
let item_id = $(this).data(‘delete_id’);
$(‘.item_id_’ + item_id).remove();
});
When removing the element, you must put it in the $ (document) tag for it to work.
If only write:
$(‘.btn_delete_item’).on(‘click’, function () {})
then will not work because it is in the processing area of the Javascript add script.
Download file code, just one php file: Download full code Size: 4 KB
So we have completed the example of Add and Remove input textbox with Jquery and Javascript.
Thank you for reading this article.
Your comment