2

I want the for loop to print out all the textboxes values, it doesn't work this way thought, how can I do it?

<script>
    current = x;

    for (var i = 0; i < current; i++) {    
        var num = document.calculator.textbox + i + .value;    
        document.write("<br>" + num);    
    }
</script>
<form name="calculator">
    <input type="text" name="textbox1">
    <input type="text" name="textbox2">
    <input type="text" name="textbox3">
    <input type="text" name="textbox4">
    <input type="text" name="textbox5">
    <!--...... infinite amount of textboxes-->
</form>
Lion
  • 18,729
  • 22
  • 80
  • 110
  • @Quentin, doesn't look like to me. – Tomas Jun 09 '13 at 13:48
  • It would just be `read_prop(document.calculator, "textbox"+ 1);` Little extreme, but it would work. Nice explaination of [dot and bracket](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – epascarello Jun 09 '13 at 14:13

2 Answers2

5

Try to get them using brackets:

var num = document.calculator[ 'textbox' + i ].value;

So generally you can access object by two ways:

  1. Via dots: myObj.myProp
  2. Via brackets: myObj[ 'myProp' ]

Both ways are equal, but in second you can use variables + string concatenations, etc.

antyrat
  • 27,479
  • 9
  • 75
  • 76
0

This is how I would do it. I used classes instead of ids. This way it's much easier to add more inputs as you won't have to worry about incrementing the ids and changing the x var.

http://jsfiddle.net/NXPKh/2/

var tbs = document.calculator.getElementsByClassName('textbox');

for (var i = 0; i < tbs.length; i++) {
    var body = document.getElementsByTagName('body') [0];
    var br = document.createElement("br");
    var text = document.createTextNode(tbs[i].value);
    body.appendChild(br);
    body.appendChild(text);
}
Smern
  • 18,746
  • 21
  • 72
  • 90