set value to array of getElementsByName

TJ Smith picture TJ Smith · Feb 15, 2013 · Viewed 10.6k times · Source

I am having the following situation:

  • I must use dynamic table (add/remove rows) - code from http://viralpatel.net/blogs/dynamically-add-remove-rows-in-html-table-using-javascript/
  • rows contain html input boxes with name, no id
  • I need to be able to set values to these boxes
  • I have tried the following, but get into syntax problem:

    <!-- html part -> this row will be replicated by the dynamic table code -->

    <tr><td><input type=input name=mybox></td></tr>
    
    //js part - variant 1:
    document.getElementsByName("mybox").item(j).value = j;
    
    //js part - variant 2:
    document.getElementsByName("mybox")[j].setAttribute("value", j);
    

    None of these seems to work. Can you suggest a right way to do it?

    Thanks!

    Answer

    marekful picture marekful · Feb 15, 2013

    getElementsByName returns an array of HTMLElements.

    This line has the correct syntax but I doubt j, the value you are trying to set is the right index value of the returned array.

    document.getElementsByName("mybox")[j].setAttribute("value", j);
    

    The fist occurrence of j should be the index of the returned array. If It's the first element found by the given name then 0, if the 2nd, then 1, etc.