0

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;
  }
1
  • There's a perfectly fine onchange javascript property that you can set. Why attribute? and "i+j" does not exist in the html context. Commented Sep 24, 2016 at 17:06

3 Answers 3

0

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+");");
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Use

function assignFunction(i, j) {
    return function() {
        Helloworld(i+j);
    }
}
check.onchange = assignFunction(i+j);

3 Comments

Yes, It did worked. But whenever click any checkbox, '6' is the number which always gets updated. 6, which is addition of length of both arrays.
oh yeah, it's because it's evaluated when it's being run (changed).
Updated to valid answer.

Your Answer

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