3

[Golang] GopherJS DOM Example - Access Input Element Value

 2 years ago
source link: http://siongui.github.io/2016/01/11/gopherjs-dom-example-access-input-element-value/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Source Code

First we write a simple HTML for our demo:

index.html | repository | view raw

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

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK