admin 管理员组

文章数量: 1086019

I'm very new to JavaScript and I wish I could set the value of a td tag using JavaScript.

I have code like this to do so:

window.onload = function() {
     document.getElementById("units").value = "122"
}

And I have a html file like this:

<table class="table" width="100%">
    <caption class="bold">TNEB UnitCalculator</caption>
    <tbody>
        <tr>
            <td>testing</td>
            <td id="units"></td>
        </tr>
    </tbody>
</table>

But that doesn't seems to be working!

I'm very new to JavaScript and I wish I could set the value of a td tag using JavaScript.

I have code like this to do so:

window.onload = function() {
     document.getElementById("units").value = "122"
}

And I have a html file like this:

<table class="table" width="100%">
    <caption class="bold">TNEB UnitCalculator</caption>
    <tbody>
        <tr>
            <td>testing</td>
            <td id="units"></td>
        </tr>
    </tbody>
</table>

But that doesn't seems to be working!

Share Improve this question edited Feb 22, 2013 at 11:50 Cerbrus 73k19 gold badges136 silver badges150 bronze badges asked Feb 22, 2013 at 11:39 sriramsriram 9,11219 gold badges66 silver badges82 bronze badges 5
  • Do you want to set the attribute 'value' of the td or the text between the opening and closing tags? – hsan Commented Feb 22, 2013 at 11:43
  • What exactly is it you want to do? A TD doesn't have a value attribute. – Billy Moat Commented Feb 22, 2013 at 11:43
  • Need to put the data between the opening and closing tags! – sriram Commented Feb 22, 2013 at 11:43
  • end your line with semicolon ";" – EnterJQ Commented Feb 22, 2013 at 11:44
  • Have a look at stackoverflow./questions/8823498/…. – Felix Kling Commented Feb 22, 2013 at 12:07
Add a ment  | 

3 Answers 3

Reset to default 5

The td tag doesn't have a value attribute:

document.getElementById("units").appendChild(document.createTextNode(122));

Or if you want to set some attribute:

document.getElementById("units").setAttribute('data-value', 122);

The td element does not have a value attribute. Use innerHTML instead.

Actually your code is working correctly

<script>
    window.onload = function() {
        document.getElementById("units").value = "122"
    }
</script>

<table class="table" width="100%">
    <caption class="bold">TNEB UnitCalculator</caption>
    <tbody>
        <tr>
            <td>testing</td>
            <td id="units"></td>
        </tr>
    </tbody>
</table>

You can check this in your browsers developer tools. In the mand line, type:

document.getElementById("units").value

本文标签: htmljavascript doesn39t set the value of td tagStack Overflow