In the next example we will type text in a JSF h:inputText
component, and after each character is typed, a JavaScript alert box will reveal the text inserted so far.
We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.
The secret of our recipe consists in using the onkeyup
event for calling a JavaScript function. Here it is the code:
<h:head> <script type="text/javascript" language="javascript"> function getInputText(text) { alert(text.value); } </script> </h:head> <h:body> <h:inputText id="inputId" value="" onkeyup ="getInputText(this);"/> </h:body>
When a character is typed in the h:inputText
, the onkeyup
event is fired and the JavaScript getInputText
function is called. This JS function extracts the text from the JSF h:inputText
through the received argument. Notice that the this
keyword is used.