-1

Thnaks in advance. I am new in web developing and stuck in one problem. I am creating a form in which I want variable number of input fields. So I have tried to create dynamic input fields creation by taking help of some online sources. I have tried everything I could imagine but the code is not working.

So far I have written this code : index.html

<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<header>Dynamic Add Input Fields</header>
    <form name="form1" id="form1">
        <table class="table table-bordered" id="dynamic_field">
            <tr>
                <td><input type="text" name="name[]" id="name" class="form-control name_list"/></td>
                <td><input type="button" name="add" id="add" class="btn btn-success" value="ADD"></td>
            </tr>
        </table>
        <input type="button" name="submit" id="submit" value="Submit"/>
    </form>
    <script type="text/javascript" >
    $(document).ready(function () {
        var i = 1;
        $('#add').click(function () {
            i++;
            $('#dynamic_field').append('<tr id="row'+i+'"><td><input id="name" type="text" name="name[]" class="form-control name_list"/></td><td><input type="button" name="remove" id="row'+i+'" class="btn_remove" Value="X" /></td></tr>'); 
        });
        $('.btn_remove').on('click','.btn_remove',function () {
            var button_id = $(this).attr("id");
            $("#row"+button_id+"").remove();
        });

});
</script>

</body>
</html>

Now when I run this code then the output comes :

Dynamic Add Input Fields [ Input Fields ] [Add Button] [Submit Button]

So it soould work like when I click "Add" button then it should add one more input field and a "remove" button beside it.

But if I click the "Add" button, nothing happens, just URL changes.

Mahesh Suthar
  • 146
  • 1
  • 12

1 Answers1

0

You need add event handler for each new item

$('#dates').append(
    $('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>')
    .click(function(){
      // handle click
    })
);

jQuery: adding event handler to just created element

Valeriane
  • 936
  • 3
  • 16
  • 37