0
var noOfPersons;
function printEmptyBoxes() {
    noOfPersons = document.getElementById("NumberOfPeople").value;
    var dynamicAttach = document.getElementById("dynamic_Content");
    for(var i=0;i<noOfPersons;i++) {
        var name = document.createElement("input");
        var expenditure = document.createElement("input");
        var button1 = document.createElement("input");
        var button2 = document.createElement("input");

        name.setAttribute("type", "text");
        name.setAttribute("id", "person"+(i+1)+"");

        expenditure.setAttribute("type", "text");
        expenditure.setAttribute("id", "Expenditure"+(i+1)+"");

        button1.setAttribute("type", "button");
        button1.setAttribute("value", "+");

        button1.setAttribute("onclick", 'document.getElementById("Expenditure"+(i+1)+"").value += "+"');

        button2.setAttribute("type", "button");
        button2.setAttribute("value", "=");

        // button2.setAttribute("onclick", "x += eva);

        dynamicAttach.appendChild(name);
        dynamicAttach.appendChild(expenditure);
        dynamicAttach.appendChild(button1);
        dynamicAttach.appendChild(button2);
        var brk = document.createElement("br");
        dynamicAttach.appendChild(brk);
    }

}

/*
It's showing uncaught reference error unable to access i on "onclick" but my i variable is getting accessed at both of id attributes I have created before that statement("person"+(i+1)+""); */

  • for good practice, I recommend you to do something like this: button.onclick(function() {//what you want to do}) – Tree Nguyen Nov 06 '15 at 14:01

1 Answers1

0

In your case, the code is not exactly the same way you look

'document.getElementById("Expenditure"+(i+1)+"").value += "+"'

I believe what you want is have Expenditure+(i+1) (after calculate i+1) as the ID, but since it is covered by a single quote (before document and at the end), it still treat Expenditure+(i+1) (before calculate i+1) as an actual ID.

The easy way for you to check this error is look at the color of string in your editor, you will easily see that those 2 color are not the same.

So, how to fix?

Simplest way, set the ID as a different variable and use it later on

var expID = "expenditure" + (i+1);

Furthermore, don't use setAttribute for onclick event. Use .onclick() instead

button1.onclick = function_name;

Have a loop through my simple code here:

http://jsfiddle.net/mankinchi/7x6z6hgr/

Tree Nguyen
  • 1,198
  • 1
  • 14
  • 37
  • thank for you help Tree but that did not work either. I would like to share my link of entire code, just have look at it http://jsfiddle.net/chakradhari/a0ub7xqp/ – Chakradhari Jamili Nov 07 '15 at 15:38
  • You have a lot of errors in your code. For example, createElement will take "INPUT" (not "input") as an input. And if one line of code in js in wrong, the following will not run anymore. Please fix all of that – Tree Nguyen Nov 08 '15 at 00:13