yashpandey yashpandey - 2 months ago 10
Javascript Question

Dynamically create CheckBox and call a function with Onchange Event

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;
}

Answer

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+");");
Comments