JavaScript is used for a variety of tasks on the client-side. When using JavaScript with plain HTML code, we can quite easily access elements on the page. For example, the text box in the following HTML code:
[HTML]<form name="someForm" id="someForm">
<input type="text" name="someName" id="someID" value="">
</form>[/HTML]can be accessed like this:
- var textbox = document.getElementById("someID");
-
// or an alternative way via the elements array:
-
textbox = document.forms["someForm"].elements["someName"];
What if we want to use JavaScript with JSF (Java Server Faces)?
In JSF or, for that matter, any server-side generated code, we need to look at the what the code looks like on the client-side.
First of all, have a look at this code by
luxalexis:
[HTML]<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://geportal.ge.com/faces" prefix="g" %>
<f:view>
<script type="text/javascript">
function valid(form)
{
var Value = form["FormName:name"].value;
if (Value == "")
{
alert("Please enter Subject");
form["FormName:name"].focus();
return false;
}
form.submit();
return true;
}
</script>
<h:form id="FormName">
<h:outputText styleClass="jsf-output-text" value="Enter your name"/>
<h:panelGroup>
<h:inputText styleClass="jsf-output-text" id="name" value="#
{BeanName.attribute}" required="true"/>
<h:commandButton value="Submit" type="submit" styleClass="jsf-command-button"
action="#{BeanName.function}" onclick="return valid(this.form);"/>
</h:panelGroup>
</h:form>
</f:view>[/HTML]The code validates the input field (checks that it has a value entered) before the form is submitted.
The question is how do we access the text field to check. For that, we need to see how the JSF component renders on the client-side, in particular the name/id. The input field:
- <h:inputText styleClass="jsf-output-text" id="name" value="#{BeanName.attribute}" required="true"/>
generates the following:
- <input type="text" ... id="FormName:name" name="FormName:name" ...>
So, the id is converted to a name/id in the following format: [Form Name]:[id]. We can use this to access the input element. The code above makes use of the passed form variable: form["FormName:name"]. This could also have been:
- var Value = document.getElementById("FormName:name").value;
-
// or alternatively:
-
form.elements["FormName:name"].value;
Of course, the form validation could be performed via an onsubmit, i.e.
- <h:form id="FormName" onsubmit="return valid(this)">
Conclusion
We've seen how we can use JavaScript to access JSF components. The trick is to understand how JSF renders the components into HTML. Once we access the elements with JavaScript, we can validate, show/hide, and otherwise modify the elements as we can with normal HTML. This is true of any server-side generated code.
Hope you enjoy and happy coding!