submit input field using enter key

Viewed 1610

I'm building the weather app and want to submit the city name to the server using the Enter key. I am getting the error

submit is not a funtion

I want to fix this and i want to know how can i send the value to the express server in order to use it in API calls. Here's my code:

<!DOCTYPE html>
<html>
<head>
    <title>Weather APP</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <input id="City" placeholder="EnterCity" onclick="u()" action="/" method="post">
</body>
<script>
    function u(){
            document.getElementById("City").addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
        var x = document.getElementById("City");
        x.submit();
        return false;
    }
});
}
</script>
</html>
1 Answers

Try putting input inside a form tag, and submitting the form instead of the input tag

...
<body>
    <form id="CityForm" onsubmit="u()" action="/" method="post">
        <input id="City" placeholder="EnterCity" />
    </form>
</body>
<script>
    function u(){
            document.getElementById("City").addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
        var x = document.getElementById("CityForm");
        x.submit();
        return false;
    }
});
}
</script>
...

You submit form's, not individual input elements. On your input element you can have an action like onChange which will run every time the input tag get's input, but the actual submission is handled by the form

Related