0

I'm trying to dynamically add input fields based on an input field value. After adding fields, I want to add events on these dynamically added input fields, and this's what I did, but I'm not getting the result I want. Here's what I tried using jquery.

html file :

<input class='cls1' id='num' />
<div id="samp"></div>

script file

function add() {
    var num = $("#num").val()
    data = ""
    for (i = 0; i<num; i++) {
        var id_name = "input_" + i
        data += "<input class='cls2' id='" + id_name + "' /><br>"
    }
    $("#samp").show().html(data)
}

$(".cls1").on("change keyup paste", function (event) {
    console.log("chng1")
    // this's logging
    add() // this adds input fields
})

$(".cls2").on("change keyup paste", function (event) {
    console.log("chng2") // not logging
})

$("input[id^='input_']").on("change keyup paste", function (event) {
  console.log("chng2") // not logging
})

Any help would be appreciated.

user3248186
  • 1,170
  • 3
  • 15
  • 30

1 Answers1

0

Try this way :

function add() {
    var num = $("#num").val()
    data = ""
    for (i = 0; i<num; i++) {
        var id_name = "input_" + i
        data += "<input class='cls2' id='" + id_name + "' /><br>"
    }
    $("#samp").show().html(data)
}

$(".cls1").on("change keyup paste", function (event) {
 
    // this's logging
    add() // this adds input fields
})

$("#samp").on("change keyup paste",'.cls2', function (event) {
    console.log("chng2") // not logging
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='cls1' id='num' />
<div id="samp"></div>
Shree
  • 18,997
  • 28
  • 86
  • 133