无法将HTML表格单元格中的输入数据保存到JavaScript变量中

无法将HTML表格单元格中的输入数据保存到JavaScript变量中,javascript,html,css,web,Javascript,Html,Css,Web,我尝试将用户的输入放入使用HTML创建的表的单元格中,并将数据保存到JavaScript变量中 我试图将数据从表的rows单元格中一个接一个地获取到JavaScript变量,但在summit之后发出数据警报时,我得到了未定义的数据 HTML代码 <table border = "2" cellpadding = "6" cellspacing = "6" bordercolor = "white" bgcol

我尝试将用户的输入放入使用HTML创建的表的单元格中,并将数据保存到JavaScript变量中

我试图将数据从表的rows单元格中一个接一个地获取到JavaScript变量,但在summit之后发出数据警报时,我得到了未定义的数据

HTML代码

 <table border = "2" cellpadding = "6" cellspacing = "6" bordercolor = "white" bgcolor = "red" class="center" id="mytable" >
        <tr>
            <th style="background: white;">EDUCATION</th>
            <th style="background: white;">INSTITUTE</th>
            <th style="background: white;">PERCENTAGE</th>
        </tr>
        <tr>
            <td style="color: white;">10 th</td>
            <td id="10inst"><input type="text"></td>
            <td  id="10per"><input type="text"></td>
        </tr>
        <tr>
            <td style="color: white;" >12 th</td>
            <td  id="12inst"><input type="text"></td>
            <td  id="12per"><input type="text"></td>
        </tr>
        <tr>
            <td style="color: white;">Graduaction</td>
            <td  id="gradinst"><input type="text"></td>
            <td  id="gradper"><input type="text"></td>           
        </tr>
        <tr>
            <td style="color: white;">Masters</td>
            <td id="masterinst"><input type="text"></td>
            <td id="masterper"><input type="text"></td>           
        </tr>

    </table><br><br>
您必须在输入元素中添加“id”属性,而不是td元素或表元素

像这样,

<input id="12inst" type="text">

您的代码中可能有两个问题:

  • 确保只有在输入元素中输入文本后才能运行JavaScript

  • 元素中有
    元素。这意味着,当您获取
    -的elementById时,您尚未引用“”元素。“”的
    .value
    实际上是未定义的。为了解决这个问题:

    而不是

  • 做:


    完整的工作示例:

    欢迎使用SO!我想这是因为当你初始化你的变量时,输入是空的。不,如果你能给我发送html和JavaScriptYes的完整代码,这对我来说不起作用。我在这里创建了一个示例:只需在表单元格中输入文本,然后单击按钮“调用javascript”(这解决了我提到的第一个问题,即只在输入文本后运行JS),然后您将在控制台中看到输入。JavaScript代码为我提到的第二个问题提供了解决方案。
    <input id="12inst" type="text">
    
    var inst12 = document.getElementById("12inst").value;
    
    var inst12 = document.getElementById("12inst").childNodes[0].value;