[Golang] GopherJS DOM Example - Access Input Element Value


Introduction

It is really cool to run Go code in the browser. GopherJS is a compiler from Go to JavaScript, which makes this possible. In this post, we will give a simple example of DOM manipulation in Go program. This example shows how to detect the keypress of HTML input element and access the value of the input element. If you are not familiar with basic DOM manipulation in Go, read the posts in GopherJS DOM Example series first.

Install GopherJS and DOM bindings

Run the following command to install GopherJS and GopherJS bindings for the JavaScript DOM APIs:

$ go get -u github.com/gopherjs/gopherjs
$ go get -u honnef.co/go/js/dom

Source Code

First we write a simple HTML for our demo:

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - Access Input Element Value</title>
</head>
<body>

<input type="text" id="foo">
<div>Value: <span id="foo2"></span></div>

<script src="demo.js"></script>
</body>
</html>

We will attach an onkeyup event handler to the input element whose id is foo. When users type something in the input element, the content of the input element will be accessed and the value of the input element will be printed out below.

input.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import "honnef.co/go/js/dom"

func inputKeyUp(event dom.Event) {
	input := event.Target().(*dom.HTMLInputElement)

	span := dom.GetWindow().Document().GetElementByID("foo2")
	span.SetInnerHTML(input.Value)
}

func main() {
	d := dom.GetWindow().Document()
	p := d.GetElementByID("foo").(*dom.HTMLInputElement)

	p.Focus()
	p.AddEventListener("keyup", false, inputKeyUp)
}

The code is almost translated directly from JavaScript. If you are familiar with DOM manipulation in JavaScript, the code looks very similar. Now compile the Go code to JavaScript by:

$ gopherjs build input.go -o demo.js

Put demo.js together with the index.html in the same directory and open the index.html with your browser. You will type something in the input and you will see what you typed are printed out below.


Tested on: Ubuntu Linux 15.10, Go 1.5.2.