Add & Remove Textbox Dynamically in JQuery

Sometimes we have a need to add textbox dynamically in the project, this is mostly used in the web development admin panel when users don’t know the exact number of inputs.

Example: In the admin panel to add documents but the user doesn’t not the exact number of inputs, means sometimes client uploads 2 documents, sometimes he upload 4 documents, in that case we have need to create a dynamic system for user flexibility.

In JQuery we have some functions for adding html element, There are following:

1. append()

2.prepend()

3.after()

4.before()

These are the four function which we use to add html elements.

Example: To add and remove textbox dynamically

<!DOCTYPE html>
<html>
<head>
<style>
.block {
    display: block;
}
input {
    width: 50%;
    display: inline-block;
}
span {
    display: inline-block;
    cursor: pointer;
    text-decoration: underline;
</style>
</head>
 
<body>
<div class="optionBox">
    <div class="block">
        <input type="text" /> <span class="remove">Remove Option</span>
    </div>
    <div class="block">
        <input type="text" /> <span class="remove">Remove Option</span>
    </div>
    <div class="block">
        <span class="add">Add Option</span>
    </div>
</div>
 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('.add').click(function() {
    $('.block:last').before('<div class="block"><input type="text" /><span class="remove">Remove Option</span></div>');
});
$('.optionBox').on('click','.remove',function() {
            $(this).parent().remove();
});
 
</script>
</body>
</html>

 

In this example, we have used them before() function to add textbox dynamically and remove() function to remove textbox.

Categories: web designing jquery

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 25 Days

Crash : 15 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 6 Months

Fastrack : 4 Months

Crash : 2 Months

Related Blogs

Request For Demo