2

I have created a button using javascript and now I want to give it a onclick. however I want the function to have a parameter i. the problem is that when I inspect the console the onclick function is just onclick=playAudio(i). I want it to be different for each value of i in the for loop, but because it is in brackets it just stays as i instead of the current number in the for loop. I hope I have explained this properly. some of the code is below to help you understand.

var i;
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];

for(i = 0; i < audioMp3.length; i++{
    var audioBtn = document.createElement("BUTTON");
    audioBtn.setAttribute("onclick", "playAudio(i);";
}
2
  • Just use right concatenation audioBtn.setAttribute("onclick", "playAudio("+i+");" Commented Jul 21, 2017 at 6:58
  • audioBtn.setAttribute("onclick", "playAudio('+i+');"); Commented Jul 21, 2017 at 6:59

4 Answers 4

3

var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];

for(var i = 0; i < audioMp3.length; i++){
    var node = document.createElement("BUTTON");
    var textnode = document.createTextNode(audioMp3[i]);
    node.appendChild(textnode);
    node.setAttribute("onclick", "playAudio("+i+");");
    document.getElementById("element").appendChild(node);
}
function playAudio(i){
alert(i);
}
<div id="element"></div>

Sign up to request clarification or add additional context in comments.

Comments

2

I'm pretty sure that this should work :

audioBtn.setAttribute("onclick", "playAudio("+i+");");

Comments

0

audioBtn.onclick = function(){ playAudio(i) }

Comments

0

Create an array with all the possible values, loop through the values to create the buttons, each button should have their click event listener to play their own button's song.

I don't know your precise code but that is the pseudo-code to do it.

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.