Reputation: 605
I am dynamically creating a checkbox. Now I want to call a function(lets say Hello world) whenever the checkbox is checked. I used setAttribute to call the function, but I am facing problems while passing parameters. I want the values of i and j to be passed to function. Following is my code -
function addTable(message) {
var paxArray=new Array();
var mealsArray= new Array();
mealsArray=['Vegeterian Food','Non Vegeterian Food', 'Indian Continental','Chinese'];
paxArray=message.data;
for(var i=0;i<paxArray.length;i++){
var x= document.createElement('tr');
x.innerHTML=paxArray[i];
document.getElementById("Content").appendChild(x);
for(var j=0;j<mealsArray.length;j++){
var row=document.createElement('tr');
var meal=document.createElement('td');
var check_box=document.createElement('td');
var check=document.createElement('input');
check.type="checkbox";
check.id="checkbox"+i+j;
check.setAttribute("onchange","Helloworld(i+j);");
meal.innerHTML=mealsArray[j];
check_box.appendChild(check)
row.appendChild(check_box);
row.appendChild(meal);
document.getElementById("Content").appendChild(row);
}
}
}
function Helloworld(index){
document.getElementById("text").innerHTML=index;
}
Upvotes: 0
Views: 1783
Reputation: 1337
Use
function assignFunction(i, j) {
return function() {
Helloworld(i+j);
}
}
check.onchange = assignFunction(i+j);
Upvotes: 0
Reputation: 2848
You could do like this
check.setAttribute("onchange",`"Helloworld(" + (i + j) + ");"`);
If you don't use (i + j) and put just "Helloworld(" + i + j + ");", you will get concatenation and not sum
Upvotes: 0
Reputation: 770
Here i+j you are passing are simply characters not variable values.
Try:
say var i = 4; var j=3;
if you want to call Helloworld(43)
check.setAttribute("onchange","Helloworld("+i+j+");");
if you want to call Helloworld(7)
var k=i+j;
check.setAttribute("onchange","Helloworld("+k+");");
Upvotes: 1