hnvasa
hnvasa

Reputation: 860

javascript - get the correct value of the button on click

I am trying a javascript-only solution (no jQuery or no HTML-JS) where I am getting all the childNodes of a DOM element. Then I am adding a text area and a button after each of those child nodes.

Here is a simplified code snippet:

var div = document.getElementById("abc");
var children = div.childNodes;
console.log(children[1])
var child;
for(var i=1; i < children.length; i++){
    var input = document.createElement("textarea");
    input.name = "post"+i;
    children[i].appendChild(input); //add text area

    var feedbackButton = document.createElement("button");
    feedbackButton.innerHTML = "Send";
    feedbackButton.classList.add("feedbackButton" + i);
    children[i].appendChild(feedbackButton); //add button
}
feedbackButton.onclick = function() {myFunction(feedbackButton.getAttribute("class"))};

then i have the function definition as follows:

function myFunction(att) {
    console.log('You Clicked: '+ att);

If the for loop iterates 5 times, the console will always log feedbackButton5 no matter what button is pressed. I know why that is the case (since it is in for loop and overwrites the value) but I am looking for a solution where I can get the console to log the correct Button pressed class name.

Upvotes: 0

Views: 207

Answers (1)

Kavin Ruengprateepsang
Kavin Ruengprateepsang

Reputation: 314

Use const myFunction = button => () => console.log(button.getAttribute("class")) to create myFunction

So you can partially apply your feedbackButton in the for loop. It works because you store it in function scope instead of referencing it at the calling time.

<html>
<body>
    <div id="abc">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>
    <script>
        const myFunction = button => () => console.log(button.getAttribute("class"));

        var div = document.getElementById("abc");
        var children = div.children;
        for(var i=0; i < children.length; i++){
            var input = document.createElement("textarea");
            input.name = "post"+i;
            children[i].appendChild(input);
        
            var feedbackButton = document.createElement("button");
            feedbackButton.innerHTML = "Send";
            feedbackButton.classList.add("feedbackButton" + i);
            children[i].appendChild(feedbackButton);
            feedbackButton.onclick = myFunction(feedbackButton);
        }
    </script>
</body>
</html

Upvotes: 1

Related Questions