-2

I am creating number of buttons depending upon length of records . So number of buttons will change when record will change every time I will run program. Here is my code of it .

for (var i = 0; i < labels.length; i++) {
<button type="button" id='+i+'>'+i+'</button>';
}

It will create buttons 1,2,3,4,5....up-to length of labels. Now problem is that I want to assign them id and onclick. On everyonclick It will pass value to a function which button was press like I will pass 1 if 1st button was pressed and 2 if 2nd button is pressed. How I can do it ? I saw that Question that reported as duplicate question but he is using jquery and not passing any values to new function based on Id (which is my main problem) .

Community
  • 1
  • 1
Pro-Web
  • 23
  • 11

4 Answers4

2

Try this:

<button type="button" class="mybtn" id='+i+'>'+i+'</button>';

the button have a common class mybtn and with incremented id value in it.

And you can assign event listener to it like:

$(document).on('click', '.mybtn', function(){
    alert( $(this).attr('id') );
    // Will give the id value for the clicked button
});
Mayank Pandeyz
  • 23,243
  • 3
  • 29
  • 52
2

Below is something that you want:

var buttons="";
for (var i = 0; i < 10; i++) {
  buttons+='<button type="button" id='+i+' onClick="alert('+i+');">'+i+'</button>';
}
document.getElementById('area').innerHTML = buttons;
<div id="area"></div>

UPDATE You can call any function in the onClick handler and pass any value you want.

Shakti Phartiyal
  • 5,370
  • 2
  • 19
  • 42
0

Try this simple javascript onclick function

for (var i = 0; i < 10; i++) {
document.body.innerHTML +='<button type="button" id='+i+' onclick="test(this)">'+i+'</button>';
}
 function test(that){
 console.log(that.id+'  was passed')
 
 }
prasanth
  • 19,775
  • 3
  • 25
  • 48
0

Since this buttons are dynamically created you need to delegate the event

for (var i = 0; i < 6; i++) {
   // some parent element to hold the buttons
  $('#buttonHolder').append('<button class ="buttonClass" type="button" id=' + i + '>' + i + '</button>');
}

 //on click delegate the event to button
$('body').on('click', '.buttonClass', function() {
  console.log($(this).attr('id'))

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='buttonHolder'></div>
brk
  • 43,022
  • 4
  • 37
  • 61