1

First, I am not too verse with JavaScript. I would like to build a HTML table TD elements with content dynamically using JavaScript. Here is my code that is not working properly.

<script type="text/javascript">
function changed(num){
    a1=num;
    a2=num+1;
    a3=num+2;

    for(var i=1;i<=3;i++){
       document.getElementById("boxA"+i).innerHTML=eval('a'+i);
    }
}
</script>

Here is the HTML code:

<input type="text" name="box" onChange="changed(this.value);">

<table width="400" border="10" cellpadding="5">
<tr>
    <td id="boxA1">&nbsp;</td>
    <td id="boxA2">&nbsp;</td>
    <td id="boxA3">&nbsp;</td>
</tr>
</table>

If I entered the value 1 in the input field, the following values should be 1, 2, 3

1
  • What error do you get? Commented Apr 14, 2014 at 16:40

2 Answers 2

3

The + operator will always perform concatenation when a String is given to it, which the value of an <input> will always be:

console.log('1' + 1);
// '11'

console.log(1 + '1');
// '11'

You'll have to convert the value to a Number to perform addition:

<... onChange="changed(parseFloat(this.value));">

You should also consider using an Array or Object to collect related values, especially those you need to iterate over:

function changed(num){
    var a = {
        1: num,
        2: num + 1,
        3: num + 2
    };

    for(var i=1;i<=3;i++){
       document.getElementById("boxA"+i).innerHTML = a[i];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 surprisingly the value of an input of type number is also a string.
0

Here is a simple approach ....

function changed(n){

  n = parseInt(n); // convert to integer
  if (!n) { return; } // end execution if not found (if not a number)

  for (var i = 1; i <= 3; i++) {

    // Since there is no HTML, textContent is better
    // eval is not needed (people often say eval is evil) ;)
    // using the i to increment
    document.getElementById('boxA' + i).textContent = n + i -1;
  }
}

Good luck :)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.