0

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());
});
1
  • Does the console log the same value for all the button click event or you say the console log happens only on first button click Commented Sep 22, 2016 at 18:17

3 Answers 3

1

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

$(document.body).on('click','.button', function(e) { 
    console.log($(this).val());
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

and use e.target.id for checking whether which is called
0

Problem: Is with this part of code console.log($('.button').val()); The part $('.button') selects all the buttons , But when you say .val() it defaults to the first one out of the collection. Hence you see the same output on all the button clicks.

Solution: Change the code to log the current clicked button value by using $(this).val(). this will refer to the element that triggered the event.

So the final line of code should be

console.log($(this).val());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.