Dynamically Add Field using jQuery

Spread the love

Project :- Dynamically Add Field using jQuery

Solution

  • Difficulty – Easy
  • Files – 2
  • Index.html & own.js
  • CDN Used

Index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Dynamic Field Add - By Hindialerts.com</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css">
    <style type="text/css">

    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8">
                <form action="" method="post">
                    <fieldset>
                        <ul class="list-unstyled" id="sites">
                            <li>
                                <label>Name</label><input type="text" value="" class="form-control" />
                            </li>
                        </ul>
                        <input class="btn btn-danger" type="button" id="add" value="Add More" />
                    </fieldset>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="own.js"></script>
</body>

</html>

own.js

$(document).ready(function () {
    $(document).ready(function () {
        $('#add').click(function () {
            var str = '<li class="list-item">';
            str += '<label>Name</label><input class="form-control mb-2" type="text" value=""/> ';
            str += '<input type="button" class="btn btn-danger float-right mb-2 remove" value="remove" /> ';
            str += '</li>';
            $('#sites').append(str);
        });
        $(document).on('click', '.remove', function () {
            $(this).parent('li').remove();
        });
    });
});

This is only for learning purpose that you can understand easily. If you get any error or want to something new to learn share details below.

Other Important Topics

Be the first to comment

Leave a Reply

Your email address will not be published.


*