1

I have table and javascript code which should change the value of each input in table. How can I get access to inner cell element?

This is my html code:

<table border="1" id="myTable">
  <tr>
     <th><input type="text" size="2"></th>
     <th><input type="text" size="2"></th>
     <th><input type="text" size="2"></th>
     <th><input type="text" size="2"></th>
     <th><input type="text" size="2"></th>
     <th><input type="text" size="2"></th>
  </tr>
</table>

And this is my javascript code:

function showSuccess(msg) {
    Messenger({
        extraClasses: 'messenger-fixed messenger-on-right messenger-on-top',
        theme: 'flat'
    }).post(msg);
}

function pushArray(){

    var oTable = document.getElementById('myTable');

    //gets rows of table
    var rowLength = oTable.rows.length;

    //loops through rows
    for (i = 0; i < rowLength; i++) {
        //gets cells of current row
        var oCells = oTable.rows[i].cells;

        //gets amount of cells of current row
        var cellLength = oCells.length;

       //loops through each cell in current row
       for(var j = 0; j < cellLength; j++){

            // here i should change the value of input
            oCells[j].innerHTML="NEW CONTENT";
        }
    }
}
1
  • Shouldn't you use td instead of th? Also have you tried stepping through this with the debugger? Commented Mar 2, 2017 at 21:02

2 Answers 2

2

you should try to find the textbox you have added inside your header tag

oCells[j].getElementsByTagName("input")[0].value = "your value";

Working fiddle here https://jsfiddle.net/bsmdr2hq/2/

Sign up to request clarification or add additional context in comments.

Comments

0

This code works, make sure to include the javascript file and set the onload property of the body.

<html>
    <head>
        <script src="test.js"></script>
    </head>
    <body onload="pushArray()">
        <table border="1" id="myTable">
          <tr>
             <th><input type="text" size="2"></th>
             <th><input type="text" size="2"></th>
             <th><input type="text" size="2"></th>
             <th><input type="text" size="2"></th>
             <th><input type="text" size="2"></th>
             <th><input type="text" size="2"></th>
          </tr>
        </table>
    </body>
</html>

1 Comment

Why do you think the code works? It replaces the HTML of the table cell, instead of filling in the value of the input.

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.