0

I'm trying to get into a set of inputs values using TagName and store only even numbered ones in a table with the position. It seems like there is an error.

function call() {
  var v = document.getElementsByTagName('input');
  var s = '<table border = 1><tr><td>position<td>value</tr>';
  for (var i = 0; i <= v.length; i++) {

    var p = v[i].value;
    console.log(p);

    if (p % 2 === 0) {

      s += '<tr><td>' + i + '<td>' + p + '</tr>';
    }
  }
  s += '</table>'
  document.getElementById('result').innerHTML = s;
}
<p>elm 1 : <input type="texte" name="" value="10"></p>
<p>elm 2 : <input type="texte" name="" value="12"></p>
<p>elm 3 : <input type="texte" name="" value="10"></p>
<p>elm 4 : <input type="texte" name="" value="12"></p>
<button onclick="call()">calculat</button>
<hr>
<p id="result"></p>

jsBin for my code

Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
  • 1
    In your `for` loop, replace `i <= v.length` by `i < v.length`, you're doing 1 extra loop. And you're missing 2 closing ``, inside that loop – blex Dec 19 '19 at 22:13
  • 1
    ... and 2 at the beginning, too. Also, you're inserting a `table` inside a `p`, which is [not valid HTML](https://stackoverflow.com/a/9852381/1913729). And in your page HTML, `type="texte"` should be `type="text"` – blex Dec 19 '19 at 22:20
  • hi, think you for helping me, just i want to start from 1 in position – Abdelhak Boumezrag Dec 19 '19 at 23:20
  • So your problem is that the numbers are off by one? – Andrew Myers Dec 19 '19 at 23:23
  • I don't have time to write an answer, but you should probably start with `i = 0`. JavaScript arrays start with 0, so it's easier on the code side if you always start with 0. At the bottom where you generate the table, you can replace the `+i+` with `+(i+1)+`. That will make the position numbers look normal (by starting with 1). – Andrew Myers Dec 19 '19 at 23:32
  • oook think you very much i do that but i missed the () ...hahaha im sorry im super beginner dont be angry plz....think you – Abdelhak Boumezrag Dec 19 '19 at 23:42
  • Since you're a beginner, I'll give you a link to explain more about why the () is necessary: [Javascript + sign concatenates instead of giving sum of variables](/a/5961029/5764553) – Andrew Myers Dec 20 '19 at 04:48
  • think you very much it helpfull – Abdelhak Boumezrag Dec 20 '19 at 19:26

0 Answers0