FOLLOW

Friday, March 16, 2018

How to add/remove text-box dynamically using JQuery/JavaScript?

This example demonstrates how to add/remove text field in the form dynamically. I saw so many examples on the web related to this query, but this is the simplest method in all of them.

Includes

<link rel="stylesheet"  href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>I have a blue left border.


Script

<script>
    $(document).ready(function () {
        //maximum input boxes allowed
        var max_fields = 5;
        //Fields wrapper
        var wrapper = $(".input_fields_wrap");
        //Add button
        var add_button = $(".add_field_button");

        //Initlal text box count
        var x = 1;
        //On add input button click
        $(add_button).click(function (e) {
            e.preventDefault();
            //Max input box allowed
            if (x < max_fields) {
                //Text box increment
                x++;
                //Add input box
                $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field btn-danger">Remove</a></div>');
            }
        });
        //User click on remove text
        $(wrapper).on("click", ".remove_field", function (e) {
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
        })
    });
</script>


Styles

<style type="text/css">
    body{
        position: absolute;
        width: 600px;
        height: 200px;
        z-index: 15;
        top: 50%;
        left: 30%;
        margin: -100px 0 0 -150px;
    }
    .box{
        background: grey;
        padding-top: 10px;
        padding-left: 60px;
        padding-bottom: 10px;
        width: 500px;
        height: auto;
    }
    .btn-success{
        padding: 5px;
    }
    input{
        margin-top: 10px;
    }
</style>


Body

<body>
    <div class="input_fields_wrap box">
        <a href = "http://www.phpjavascript.com/" class="btn-success">Add</a>
        <button class="add_field_button btn-success">Add More Fields</button><br>
        <input type="text" name="mytext[]"><br><br>
<a href = "http://www.phpjavascript.com/" class="btn-success">More</a>
    </div>
</body>


Result


3 comments:



  1. This is exactly what I was looking for. Thanks for sharing this great article!
    That is very interesting Smile I love reading and I am
    always searching for informative information like this!

    https://idkapparel.com/

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete