如何将数据从HTML表单传输到JavaScript函数?

时间:2013-08-02 16:35:48

标签: javascript html

我正在尝试创建一个接受用户值的表单,然后将这些值传递给同一文件中的JS函数进行某些计算。我现在只是想将值打印到控制台,但我不断收到错误"Object #<HTMLDocument> has no method 'getElementByID'"。这是代码:

<!DOCTYPE html>
<html>
<body>

<form action="javascript:formHandler();" method="get">
    <h1 align="center">Set the parameters you would like to visualize</h1>

    Center Frequency: <input type="text" name="cf" id="cf"><br>
    Bandwidth: <input type="text" name="bw" id="bw"><br>
    Number of Bins: <input type="text" name="bins" id="bins"><br>
    Number of Values to be Visualized: <input type="text" name="values" id="values"><br>
    <input type="submit" value="Submit">
</form>
<script>


    function formHandler()
    {
            console.log(document.getElementByID("cf")); // This is where I'm getting the error
    }

</script>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

存在拼写错误。它应该是getElementById而不是getElementByID

您可以将值打印到控制台,如下所示:

console.log(document.getElementById("cf").value);

答案 1 :(得分:2)

你的document.getElementByID最后应该有小写 d,你也应该添加.value,就像这样

document.getElementById("id").value

获取传递或输入的值

答案 2 :(得分:1)

如果你喜欢这个,那就更好了

<form action='somepage.html' OnSubmit="return formHandler();" method="get">
<h1 align="center">Set the parameters you would like to visualize</h1>

Center Frequency: <input type="text" name="cf" id="cf"><br>
Bandwidth: <input type="text" name="bw" id="bw"><br>
Number of Bins: <input type="text" name="bins" id="bins"><br>
Number of Values to be Visualized: <input type="text" name="values" id="values"><br>
<input type="submit" value="Submit">
</form>


<script type='text/javascript'>
function formHandler()
{
        console.log(document.getElementById("cf").value);
  return true;
}
</script>