Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

javascript - submit input field using enter key

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>
question from:https://stackoverflow.com/questions/65838105/submit-input-field-using-enter-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...