0

Adding the click event for dynamically created buttons

I have included the id(same for all buttons) for dynamically created buttons and then calling the click funtion based on the id When I click the button it should display the value of the button in the web page.

var elements = [];
for (i in values) {
    var timeBut= $('<div class="col-md-2 top-space-20"><input type="button" 
    id="timebutt" class="btn" value="the value fetching from the back end"> 
    </div>');
     elements.push(timeButt);

<script>
$("document").ready(function () {
$("#timeButt").click(function (){
     msg1 = "The free time slot is" + ("#value")
});
})
$("#resultDiv1").html(msg1);
</script>
Pete
  • 57,112
  • 28
  • 117
  • 166

2 Answers2

0

You don't need ids for that, just use event target:

$(".btn").click(function(event){
     var msg = "The free time slot is" + event.target.value;
     $("#resultDiv1").html(msg);
});
Gvz
  • 11
  • 2
0

Giving same id to multiple elements is not a good idea. Use classes instead and jQuery would be happier. I don't know exactly what you're trying to achieve, anyway you can manage click event on dynamic button mainly in 2 ways:

Use onclick direcly on element:

var timeBut= $('<div class="col-md-2 top-space-20"><input type="button" id="timebutt' + i + '" class="btn" value="the value fetching from the back end" onclick="timebutt_click(' + i + ')"></div>');
...
function timebutt_click(value){
    msg1 = "The free time slot is" + value;
...
}

Bind later using class:

var timeBut= $('<div class="col-md-2 top-space-20"><input type="button" class="btn timebutt" value="the value fetching from the back end" data-value="' + i + '"></div>');
...
$(".timebutt").click(function(){
   msg1 = "The free time slot is" + $(this).data("value");
});

In this case I stored the value binded to button on a data attribute, to that I can retrive later. In the first case this is not needed cause the value is passed directly as parameter of the onclick function.

id for the button may or not be needed. In case, assure it's unique, adding some unique it to a base name (see first example).

Massimo
  • 90
  • 1
  • 8
  • This solution helped me.I have included onclick for my buttons.Thanks –  Aug 01 '19 at 15:50