[HTML]<form name="someForm" id="someForm">
<input type="text" name="someName" id="someID" value="">
</form>[/HTML]can be accessed like this:
Expand|Select|Wrap|Line Numbers
- var textbox = document.getElementById("someID");
- // or an alternative way via the elements array:
- textbox = document.forms["someForm"].elements["someName"];
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:
Expand|Select|Wrap|Line Numbers
- <h:inputText styleClass="jsf-output-text" id="name" value="#{BeanName.attribute}" required="true"/>
Expand|Select|Wrap|Line Numbers
- <input type="text" ... id="FormName:name" name="FormName:name" ...>
Expand|Select|Wrap|Line Numbers
- var Value = document.getElementById("FormName:name").value;
- // or alternatively:
- form.elements["FormName:name"].value;
Expand|Select|Wrap|Line Numbers
- <h:form id="FormName" onsubmit="return valid(this)">
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!