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


No comments:

Post a Comment

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts