Is there a way to use EL to get the current value of an h:inputText field? - jsf

I'm new to JSF and EL, and was wondering if there is a way to use EL to get the current value of an h:inputText field. Am I doing it wrong, or is it possible at all?
Thanks,
-Ben

(Based on your comment) If you want to validate it server-side then you should look at an Ajax library like Richfaces.
You can then easily add an ajax call to your input field
<h:inputText id="myInput" value="#{myBean.myValue}">
<a4j:support event="onchange" ajaxSingle="true"/>
</h:inputText>
When you change the text the Ajax call will update your model on the Server-side. If you have a validator then you can add it to the inputText tag or use the action attribute on the support tag to call another method.

I don't really understand what you are looking for...
With this code:
<h:form id="myForm">
<h:inputText id="myInput" value="#{myBean.myValue}"/>
The value of the input field, at the creation of the HTML page, will be equal to the value of the myValue property of the bean myBean.
If the value is changed by the user, JSF will automatically update the value of myBean.myValue when the form will be submitted.
If you need to get the value of the input on the client side, i.e. using Javascript, you need to do the following code:
<script type="text/javascript">
function getInputTextValue() {
var valueOfInput = document.getElementById("myForm:myInput").value;
}
</script>
Note that you must prefix the ID by the ID of the form that contains the input ("**myForm:**myInput").

Related

How to trigger click event on command button in JSF, after the evalution of action EL expression [duplicate]

Problem: Sometimes you will want to access a component from javascript with
getElementById, but id's are generated dynamically in JSF, so you
need a method of getting an objects id. I answer below on how you can do this.
Original Question:
I want to use some code like below. How can I reference the inputText JSF component in my Javascript?
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>Input Name Page</title>
<script type="javascript" >
function myFunc() {
// how can I get the contents of the inputText component below
alert("Your email address is: " + document.getElementById("emailAddress").value);
}
</script>
</head>
<h:body>
<f:view>
<h:form>
Please enter your email address:<br/>
<h:inputText id="emailAddresses" value="#{emailAddresses.emailAddressesStr}"/>
<h:commandButton onclick="myFunc()" action="results" value="Next"/>
</h:form>
</f:view>
</h:body>
</html>
Update: this post Client Identifiers in JSF2.0 discusses using a technique like:
<script type="javascript" >
function myFunc() {
alert("Your email address is: " + document.getElementById("#{myInptTxtId.clientId}").value);
}
</script>
<h:inputText id="myInptTxtId" value="backingBean.emailAddress"/>
<h:commandButton onclick="myFunc()" action="results" value="Next"/>
Suggesting that the attribute id on the inputText component
creates an object that can be accessed with EL using #{myInptTxtId},
in the above example. The article goes on to state that JSF 2.0 adds
the zero-argument getClientId() method to the UIComponent class.
Thereby allowing the #{myInptTxtId.clientId} construct suggested
above to get the actual generated id of the component.
Though in my tests this doesn't work. Can anyone else confirm/deny.
The answers suggested below suffer from drawback that the above
technique doesn't. So it would be good to know if the above technique
actually works.
You need to use exactly the ID as JSF has assigned in the generated HTML output. Rightclick the page in your webbrowser and choose View Source. That's exactly the HTML code which JS sees (you know, JS runs in webbrowser and intercepts on HTML DOM tree).
Given a
<h:form>
<h:inputText id="emailAddresses" ... />
It'll look something like this:
<form id="j_id0">
<input type="text" id="j_id0:emailAddress" ... />
Where j_id0 is the generated ID of the generated HTML <form> element.
You'd rather give all JSF NamingContainer components a fixed id so that JSF don't autogenerate them. The <h:form> is one of them.
<h:form id="formId">
<h:inputText id="emailAddresses" value="#{emailAddresses.emailAddressesStr}"/>
This way the form won't get an autogenerated ID like j_id0 and the input field will get a fixed ID of formId:emailAddress. You can then just reference it as such in JS.
var input = document.getElementById('formId:emailAddress');
From that point on you can continue using JS code as usual. E.g. getting value via input.value.
See also:
How to select JSF components using jQuery?
Update as per your update: you misunderstood the blog article. The special #{component} reference refers to the current component where the EL expression is been evaluated and this works only inside any of the attributes of the component itself. Whatever you want can also be achieved as follows:
var input = document.getElementById('#{emailAddress.clientId}');
with (note the binding to the view, you should absolutely not bind it to a bean)
<h:inputText binding="#{emailAddress}" />
but that's plain ugly. Better use the following approach wherein you pass the generated HTML DOM element as JavaScript this reference to the function
<h:inputText onclick="show(this)" />
with
function show(input) {
alert(input.value);
}
If you're using jQuery, you can even go a step further by abstracting them using a style class as marker interface
<h:inputText styleClass="someMarkerClass" />
with
$(document).on("click", ".someMarkerClass", function() {
var $input = $(this);
alert($input.val());
});
Answer: So this is the technique I'm happiest with. Doesn't require doing too much weird stuff to figure out the id of a component. Remember the whole point of this is so you can know the id of a component from anywhere on your page, not just from the actual component itself. This is key. I press a button, launch javascript function, and it should be able to access any other component, not just the one that launched it.
This solution doesn't require any 'right-click' and see what the id is. That type of solution is brittle, as the id is dynamically generated and if I change the page I'll have to go through that nonsense each time.
Bind the component to a backing bean.
Reference the bound component wherever you want.
So here is a sample of how that can be done.
Assumptions: I have an *.xhtml page (could be *.jsp) and I have defined a backing bean. I'm also using JSF 2.0.
*.xhtml page
<script>
function myFunc() {
var inputText = document.getElementById("#{backBean.emailAddyInputText.clientId}")
alert("The email address is: " + inputText.value );
}
</script>
<h:inputText binding="#{backBean.emailAddyInputText}"/>
<h:commandButton onclick="myFunc()" action="results" value="Next"/>
BackBean.java
UIInput emailAddyInputText;
Make sure to create your getter/setter for this property too.
Id is dynamically generated, so you should define names for all parent elements to avoid j_id123-like ids.
Note that if you use jQuery to select element - than you should use double slash before colon:
jQuery("my-form-id\\:my-text-input-block\\:my-input-id")
instead of:
jQuery("my-form-id:my-text-input-block:my-input-id")
In case of Richfaces you can use el expression on jsf page:
#{rich:element('native-jsf-input-id')}
to select javascript element, for example:
#{rich:element('native-jsf-input-id')}.value = "Enter something here";
You can view the HTML source when this is generated and see what the id is set to, so you can use that in your JavaScript. As it's in a form it is probably prepending the form id to it.
I know this is not the JSF way but if you want to avoid the ID pain you can set a special CSS class for the selector. Just make sure to use a good name so that when someone reads the class name it is clear that it was used for this purpose.
<h:inputText id="emailAddresses" class="emailAddressesForSelector"...
In your JavaScript:
jQuery('.emailAddressesForSelector');
Of course you would still have to manually manage class name uniqueness.
I do think this is maintainable as long as you do not use this in reusable components. In that case you could generate the class names using a convention.
<h:form id="myform">
<h:inputText id="name" value="#{beanClass.name}"
a:placeholder="Enter Client Title"> </h:inputText>
</h:form>
This is a small example of jsf. Now I will write javascript code to get the value of the above jsf component:
var x = document.getElementById('myform:name').value; //here x will be of string type
var y= parseInt(x,10); //here we converted x into Integer type and can do the
//arithmetic operations as well

Post value using h:inputtext and a4j:support onkeyup

I was originally posting a value in the h:inputText field with an a4j:commandButton but I had to change the commandButton to s:link because the commandButton is also triggering a pdf document to be exported, and I believe that with an ajax call, the doc is rendered on the browser instead.
So now I am trying to post the value using h:inputText and a4j:support
<h:inputText id="numberOfPatients"
value="#{printLabelsReqFormsAction.numberOfPatients}">
<a4j:support event="onkeyup"
action="#{printLabelsReqFormsAction.setNumberOfPatients(numberOfPatients)}"/>
</h:inputText>
(sorry for the weird formatting..)
My setNumberOfPatients(x) is getting called but I don't think I am passing the value correctly. How should I pass the value of the h:inputText field?
You don't need to explicitly set the value of numberOfPatients while executing ajax support. a4j:support tag processes its parent component during its execution, meaning the value for numberOfPatients will be set for each onkeyup event, even you don't invoke an action event. You can see it better at Richfaces' site:
RichFaces uses form based approach for Ajax request sending. This means each time, when you click an Ajax button or produces an asynchronous request, the data from the closest JSF form is submitted with the XMLHTTPRequest object. The form data contains the values from the form input element and auxiliary information such as state saving data.
When "ajaxSingle" attribute value is "true" , it orders to include only a value of the current component (along with or <a4j:actionparam> values if any) to the request map. In case of <a4j:support> , it is a value of the parent component. An example is placed below:
<h:form>
<h:inputText value="#{person.name}">
<a4j:support event="onkeyup" reRender="test" ajaxSingle="true"/>
</h:inputText>
<h:inputText value="#{person.middleName}"/>
</form>
In other words, for your case this should work:
<h:inputText id="numberOfPatients"
value="#{printLabelsReqFormsAction.numberOfPatients}">
<a4j:support event="onkeyup" ajaxSingle="true"/>
</h:inputText>
Specify an action method only if you want to add extra logic when the event happens.

Rendering a data-table only when the bean returns a list

I have been trying to render a rich:dataTable, but fails, when it comes to its conditional rendering.I wanted to render it only if the size of the list, the backing-bean fetches from DB, is greater than zero.
JSF-2.0, RichFaces-4 are what i use.
You have to use the "render" attribute of the datatable. With it you can define if the component is rendered to the client or not. So check by EL if the list is populated.
you can do something like:
rendered="#{not empty listObject}"
and all is fine.
I always implement my database query method to never return null, if the query has no result I return an empty list. This way i'm sure I never get a nullpointerexception and I prefer then to show an empty table. Because it's easer to layout the page, when you are sure the table always exist.
Hope that helps.
The scenario is I have a groupId which I rightclick on. On the context menu, I choose Display CTNs and it should then render all the CTNs of this group in a data-table. It starts with a JavaScript call, which I call once I choose "Display CTNs". It takes care of supplying the GroupId to the a4j:jsFunction.
<rich:dataTable value="#{ctnGrpMgmtController.ctnDetailsList}"
var="ctnVar" id="ctnTable" rows="5"
rendered="#{not empty ctnDetailsList}">
The above should be rendered after the below a4j:jsFunction executes.
<a4j:jsFunction name="selectGroupForManagingCtns"
action="#{ctnGrpMgmtController.loadCTNsForAGroup}"
render="ctnListPanel,ctnTable">
<a4j:param name="name"
assignTo="#{ctnGrpMgmtController.groupId}" />
</a4j:jsFunction>
I have to do an F5 to see the component "ctnTable", which is where the problem starts.
It looks like the attribute name on the a4j:jsFunction is reRender instead of just render. Should fix it.

Javascript error in XHTML page in JSF 2

I have the following code in an xhtml page in JSF 2. But when the page loads I get an javascript error that
document.getElementById("country") is null or not an object.
Why is this happening?
<h:form>
<h:panelGrid columns="2">
Selected country locale :
<h:inputText id="country" value="#{country.localeCode}" size="20" />
Select a country {method binding}:
<h:selectOneMenu value="#{country.localeCode}" onchange="submit()"
valueChangeListener="#{country.countryLocaleCodeChanged}">
<f:selectItems value="#{country.countryInMap}" />
</h:selectOneMenu>
<script>
alert("hi");
document.getElementById("country").disabled=true;
</script>
</h:panelGrid>
</h:form>
It's not finding your component. Since your <h:inputText> is inside of an <h:form> the id will have the following pattern
formName:componentName. Since you did not specify an id for <h:form>, JSF will generate one for you. That's why you are seeing j_id1926454887_72d35e53:country where j_id1926454887_72d35e53 is the form id. If you want to deal with simpler id, then you should add an id value to your <h:form>. For example
<h:form id="form">
<h:inputText id="country" value="#{country.localeCode}" size="20" />
</h:form>
The id for <h:inputText> will now be form:country.
Even simpler, you could simply add prependId = "false" to your form
<h:form prependId="false">
and now your id for <h:inputText> will simply be country.
How can I get this id dynamically?
I'm going to modify your code slightly to achieve what you want (I'm thinking that you want to disable the input based on a specific event). Consider this simpler example
<h:form>
<h:inputText id="country" value="#{country.localeCode}" size="20" onclick="disableInputText(this.form)" />
</h:form>
Here I'm attaching a javascript function to an HTML DOM Event handler. In this case, I want the input to be disabled when I click on it (hence onclick). I'm also passing the form as a reference in the function. Then, define your Javascript like this.
<script>
function disableInputText(form) {
form[form.id + ":country"].disabled = true;
}
</script>
We simply grab the input in the javascript with the corresponding id via the object form and set its disabled attribute to true. (You can sort of view the form object as Map).
Also check the link below for more attributes of <h:inputText> and the different handlers you can use (the ones with on as prefix).
inputText Tag Attribute.
Also, check out the answer with the most votes to get a bigger picture on how ids are generated and other ways on how they can be determined.
How can I know the id of a JSF component so I can use in Javascript
It's seems to be a naming issue. the id of the field is not rendered as country.
i found a question that seems relevant. Composite components & ID

commandlink in JSF not generating the intended HTML tag

I'm trying to call a managed bean from h:commandLink in JSF. But I don't see href attribute in the rendered HTML a tag.
Am I missing something?
There is a ManagedBean called AccountSetupController with a signUp method in it.
This is the tag I used in JSF:
<h:form prependId="false">
<h:commandLink action="#{accountSetupController.signUp()}"
value="#{msg['homepage.createaccount']}" styleClass="button large">
</h:commandLink>
</h:form>
This is the rendered tag. See there is nothing in href attribute.
<a href="#" onclick="mojarra.jsfcljs(document.getElementById('j_idt15'),
{'j_idt33':'j_idt33'},'');return false"
class="button large">CREATE MY ACCOUNT</a>
This is the form tag that is generated
<form id="j_idt15" name="j_idt15"
method="post" action="/myproject/faces/homepage/homepage.xhtml"
enctype="application/x-www-form-urlencoded"> .... </form>
As you can see, the form action is pointing to some place I don't need.
Am I missing something?
Command links in JSF are rendered that way. The form will be submitted by JSF via JavaScript's onclick method using JSF JS library, while the href will always stay #.
Moreover, you won't find the bound action / action listener method names in browser tools due to understandable reasons. Rather, JSF will find the id of a clicked link on the server and will trigger all of the component's action(listeners).
All in all, reading <h:commandLink> documentation unsurprisingly helps a lot (all emphasis mine):
General behavior: Both the encode and decode behavior require the ability to get the id/name for a hidden field, which may be rendered in markup or which may be programmatically added via client DOM manipulation, whose value is set by the JavaScript form submit (further referred to as hiddenFieldName.
Decode behavior: Obtain the "clientId" property of the component. Obtain the Map from the "requestParameterMap" property of the ExternalContext. Derive hiddenFieldName as above. Get the entry in the Map under the key that is the hiddenFieldName. If the there is no entry, or the entry is the empty String, or the entry is not equal to the value of the "clientId" property, return immediately. If there is an entry, and its value is equal to the value of the "clientId" property, create a new javax.faces.event.ActionEvent instance around the component and call queueActionEvent() on the component, passing the event.
Encode behavior: Render "#" as the value of the "href" attribute. Render the current value of the component as the link text if it is specified. Render JavaScript that is functionally equivalent to the following as the value of the "onclick" attribute: document.forms['CLIENT_ID']['hiddenFieldName'].value='CLIENT_ID'; ocument.forms['CLIENT_ID']['PARAM1_NAME'].value='PARAM1_VALUE'; document.forms['CLIENT_ID']['PARAM2_NAME'].value='PARAM2_VALUE'; return false; document.forms['CLIENT_ID'].submit()" where hiddenFieldName is as described above, CLIENT_ID is the clientId of the UICommand component, PARAM*_NAME and PARAM*_VALUE are the names and values, respectively, of any nested UIParameter children.

Resources