简体   繁体   中英

How to transfer data from an HTML form to a JavaScript function?

I'm trying to make a form which accepts values from the user and then passes those values to a JS function in the same file for some calculations. I'm just trying to print the values to the console right now, but I keep getting the error "Object #<HTMLDocument> has no method 'getElementByID'" . Here is the code:

<!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>

There is a typo error. It should be getElementById and not getElementByID .

You can print the value to console as below:

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

your document.getElementByID should have a lowercase d at the end and you should also add .value, like so

document.getElementById("id").value

to get the value of whats being pass or typed

Better if you do like this

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM