| Refresh | Home EGTry.com

get input through gwt dom api


The following example show
1. expose a java static method as javascript function
2. (from java) get user input value through gwt java api

GWT Entry Point class

package egtry.client;


import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.user.client.DOM;


public class ClientApp1 implements EntryPoint {



	public void onModuleLoad() {
		updateSum();
		
		registerFunctions();

	}
	
	public static native void info(String msg) /*-{
	   $wnd.alert(msg);
	}-*/;
	
	
	public static native void registerFunctions() /*-{
		$wnd.updateSum=$entry(@egtry.client.ClientApp1::updateSum());
	}-*/;
	
	
	public static void updateSum() {
		InputElement num1=(InputElement)(Element)DOM.getElementById("num1");
		InputElement num2=(InputElement)(Element)DOM.getElementById("num2");
		InputElement result=(InputElement)(Element)DOM.getElementById("result");
		
		int sum=Integer.parseInt(num1.getValue())+Integer.parseInt(num2.getValue());
		result.setValue(""+sum);
	}
}


main html

<html>
  <head>
    <script type="text/javascript" language="javascript" src="clientapp1/clientapp1.nocache.js"></script>
  </head>

  <body>

    <h1>implement the javascript event handler in java </h1>

num1:   <input id="num1" type="text" value="12" onchange="updateSum()"  /> 
num2:   <input id="num2" type="text" value="34" onchange="updateSum()" /> 
result: <input id="result" type="text" disabled=1 value="" />

  </body>
</html>