Aaron Aaron - 2 months ago 6
Javascript Question

Assigning classes or ids to button created dynamically using jquery

I am creating several buttons dynamically. I am trying to assign each on a different class or id so when it is clicked on it will have a different output. How would I add an value at the end of each class or id name to give each button a unique class or id name?
Here is my code

socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for(i=0; i <data.length; i++){
$input = $('<input type="button" style="width:200px" class= "button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
});


Can I created an on click event for the all button that I created. So far I created an on click even, but it only works for the first button.
Here is my code

$(document.body).on('click','.button', function(e) {
console.log($('.button').val());
});

Answer

Use $(this).val() instead of $('.button').val(). this will refer clicked button.

$(document.body).on('click','.button', function(e) { 
    console.log($(this).val());
});