Share this page 

Read/Write HTML field values from JAVATag(s): Javascript interaction


[Netscape AND IE4 compatible]
The netscape.javascript.* (LiveConnect) package provides facilities to directly manipulate HTML FORM components.
JSObject win = (JSObject)JSObject.getWindow(this);
JSObject inputText = (JSObject) win.eval("document.forms[0].elements[0]");
String value = (String)inputText.getMember("value");  // read form value
inputText.setMember("value" , value + " new stuff");  // write form value
But this action requires a signed applet. in Netscape, you must
PrivilegeManager.enablePrivilege("UniversalBrowserRead");
PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
before using an JSObject related to an HTML document.

But there is a workaround, simply pass the informations through Javascript functions!

[JSjava.java]

import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import netscape.javascript.*;

public class JSjava extends Applet
     implements ActionListener {
 Button b1,b2;
 TextField tf;

 JSObject win;

 public void init(){
  setLayout(new FlowLayout());
  tf = new TextField(10);
  b1 = new Button("to FORM");
  b2 = new Button("from FORM");

  b1.addActionListener(this);
  b2.addActionListener(this);
  add(tf);add(b1);add(b2);
  }

 public void actionPerformed(ActionEvent ae) {
  if (ae.getSource() == b1) {
     // send TO FORM
     JSObject win = (JSObject)JSObject.getWindow(this);
     win.eval("setHTMLInputText('"+tf.getText()+"');");
     }
  if (ae.getSource() == b2) {
     // receive FROM FORM
     JSObject win = (JSObject)JSObject.getWindow(this);
     tf.setText((String)win.eval("getHTMLInputText();"));
     }
  }
}

[JSjava.html]

<HTML><HEAD>
<SCRIPT>
function getHTMLInputText(){
  return document.forms[0].elements[0].value;
  }
function setHTMLInputText(s){
  document.forms[0].elements[0].value = s;
  }
</SCRIPT></HEAD><BODY>
<FORM>
  <INPUT TYPE=text SZIE=20>
</FORM>

<APPLET NAME="JS" CODE=JSjava.class MAYSCRIPT WIDTH=200 HEIGTH=200>
</APPLET></BODY></HTML>
For best result, never use LiveConnect JSObject in Applet's init() method.