简体   繁体   中英

How to detect user input into a form on a webpage

I am trying to detect if the user enters something on a webpage hosted by golang but every time the user clicks the button and submits the form it just redirects to a different page (I am hosting on localhost:8080 and it redirects to localhost:8080/text). I am pretty sure this is because the form action is set to "/text" but if I remove that the golang handlefunc is never run. Here is what I have so far:

package main

import (
  "log"
  "net/http"
  "fmt"
)

func main()() {
  //runs server
  fs := http.FileServer(http.Dir("./"))
  http.Handle("/", fs)
  log.Println("Listening...")
  http.ListenAndServe(":8080", nil)
  //detects user input and calls function
  http.HandleFunc("/text", textGetter)
}

func textGetter (w http.ResponseWriter, r *http.Request) () {
  r.ParseForm()
  text := r.PostFormValue("text")
  fmt.Fprintf(w, "this: %s", text)
  fmt.Print(" was written in the text box")
}

and this html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>hello</title>
    <link rel="stylesheet" href="./stylesheet.css">
  </head>
  <body>
    <h1>Write something bellow</h1>
    <form class="userText" action="/text" method="post">
      <input type="text" name="textbox" id="textBox" value="" placeholder="type something here">
      <input type="submit" value="text" name="button" id="button" onclick="thank(message.value)">
    </form>
    <script type="text/javascript" src="./script.js"></script>
  </body>
</html>

Can someone tell me what's wrong?

It's a front end task independent of Go or any other language.

You may track user input adding onkeypress attribute to the interesting field. You need some Ajax library. For example you may take jQuery .

Try code similar to:

<input ... onkeypress="input()">
<script>
       function input(){
            $.ajax(url, parameters)
       }
 </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