im newbie in Jquery , i want to do a placeholder in jsf , something like this : http://niklaskoehler.de/demos/vordefinierter-text/ . I've the next code :
<head>
<script type="text/javascript">
jQuery(document).ready(function() {
var $ = jQuery;
var Element = "#email";
var InputText = "Placeholder demo";
$(Element).val(InputText);
alert("sup bro"); //this alert works
$(Element).bind('focus',function(){
$(this).addClass('focus');
if($(this).val()==InputText){
$(this).val('');
}
}).bind('blur',function(){
if($(this).val()==""){
$(this).val(InputText);
$(this).removeClass('focus');
}
});
});
</script>
</head>
And this is my form :
<h:form>
<div class="form-item">
<h:inputText id="email" title="Email" value="#{UserAction.email}"/>
</div>
</h:form>
And nothing happen with the input , what is wrong in my code?
jQuery doesn't work with JSF component tree in server side. Instead, it works with HTML DOM tree in client side. In case of JSF, you should instead be looking at JSF-generated HTML output while writing jQuery. As you're encountering rather unpredictable HTML element IDs like pbGfb9435b3_2d720d_2d478d_2d8183_2d657b3839216b_j_id1:j_idt5:email, you're likely running a JSF portlet instead of servlet. The pgXxx ID prefix occurs on portlets only.
As a word of advice, don't select non-unique elements by ID. Select by class name instead.
E.g.
<h:inputText ... styleClass="email" />
with
var selector = ".email";
var inputText = "Placeholder demo";
$(selector).val(inputText);
(I took the liberty to fix poor variable names; they should not start with uppercase and the CSS selector is not an element)
See also:
How to refer to a JSF component Id in jquery?
How to select JSF components using jQuery?
Sark,
Execute your web page and viewsource for same.
Whatever ID you will find for your <input type='text' id='something'
add the same id to your Jquery
var Element = "#something";
I'm trying to change an JSF 1.1 page to conditionally hide parts of the page. The page is built using intermixed raw HTML and tags. Specifically I have the following:
<table>
<tr>
<td>Foo</td>
<td><h:inputText ... /></td>
</tr>
<tr>
<td>Bar</td>
<td><h:inputText ... /></td>
</tr>
<!-- more stuff, including <h:dataTable>
</table>
I would like to wrap this in a tag that conditionally hides this entire table, but I cannot seem to figure it out. Here's what I've tried:
Wrap the markup in a <h:panelGroup rendered="...">. While this correct shows/hides the markup, all raw the HTML is stripped from the generated HTML.
Wrap the markup in a <f:verbatim>. This does not work as the verbatim tag does not have a rendered attribute in JSF 1.1
Wrap the whole thing in a <h:panelGroup rendered="..."><f:verbatim> combo. This has the same effect as the first attempt.
I've also tried <f:view> and <f:subview> to no avail.
I know that it is possible to include JSTL tags in a JSF page and use <c:if> but I would like to avoid this situation. Any ideas?
NOTE: I realize that it is (by some at least) considered bad practice to mix HTML and JSF, however this page was created by someone else, I just have to modify it (its a somewhat large page and the HTML above is just a small snippet from it)..
Either replace <table> by <h:panelGrid>.
<h:panelGrid columns="2">
<h:outputText value="Foo" />
<h:inputText ... />
<h:outputText value="Bar" />
<h:inputText ... />
<!-- more stuff, including <h:dataTable>
</h:panelGrid>
Or make use of CSS display:none/block:
<table style="display: ${some condition ? 'none' : 'block'};">
Or just upgrade to JSF 1.2. Technically, a JSF 1.1 web application can easily be upgraded to JSF 1.2 without any code changes. It's only a matter of updating the JARs and changing the faces-config.xml root declaration to replace the JSF 1.1 DTD by a JSF 1.2 XSD. JSF 1.2 comes with an improved view handler which kills the <f:verbatim> nightmare (i.e. it is not needed anymore). It also comes with many, many bugfixes and performance enhancements you'd be very thankful for.
Unrelated to the concrete problem, as to your statement that mixing HTML and JSF is a bad practice, this isn't necessarily true. At least not since JSF 1.2 anymore. On JSF 1.0/1.1 you'd need to use <f:verbatim> which is in turn indeed a pain to develop/maintain. This caused the wrong myth that mixing JSF/HTML is "bad". See also What are the main disadvantages of Java Server Faces 2.0? for a bit of history on that.
I want to programmatically show a div tag after some processing has completed while rendering a JSP. What's the best way to do this using Java? Using jQuery I would do this:
$('#mydiv').removeClass("hide_me");
...or...
$('#mydiv').show();
How can I do this programmatically in Java while rendering the page?
Assuming you have the standard JSP setup including JSTL and have mapped it to 'c' you could just do:
<c:if test="${myCondition}">
<div id="mDiv">
content
</div>
</c:if>
It does seem from the comments like there is some confusion about rendering JSP on the server vs rendering content in the browser. Everything that happens in the JSP is server side work that has to completely finish before the browser receives the generated document and starts drawing it. You can't use JSP to change content that is already on the user's screen. You need javascript, html5, etc, for that.
With JSP Java runs on the server (unlike JavaScript that runs within browser) so conditionally render your <DIV> using Java if statement within JSP:
<% if( test="true" ) { %>
<DIV>....</DIV>
<% } %>
I think you are looking for something like this:
<div id="loader">Loading / GIF animation</div>
<div id="result" style="display:none;">
Lots of data.
Should be flushed to the browser every now and then.
This will take seconds...
</div>
<script type="text/javascript">
$("#loader").hide();
$("#result").show();
</script>
I have a form which has both HMTL tags and struts tags. I use the HTML tags because of alignment issues with struts tags.
<s:form action = "setNode" name = "processing" method ="POST">
<script>
<!--
createTree(catArray);
</script>
<br/>
<s:radio name="processOption" label="" list="{'Add','Move','Delete'}" ></s:radio>
<s:textfield name="node" ></s:textfield>
<s:submit name="Go" value=" Go " align="center" />
</s:form>
the createTree function creates a tree form with HTML checkbox input types.
The action triggers a java function. How do i see which checkboxes are checked?
Bad approach, I'd say.
First, have you taken a look at the generated html? (generated by struts, at least - if possible also generated by you javascript). It's the first thing to do, always.
Can you post it ?
Second, are you aware of "themes" in struts2 forms ? If you are using the default ("xhtml"), the form will be inside a table, and, if you are going to add some non-struts2 elements inside, you must be aware of that - for example, your <br/> tag seems out of place.
Third, Struts2 tags are always mixed with html tags, that their point. I guess you mean you are mixing input html tags (form elements) generated in javascript with others generated by the struts2 tags. In general, this is messy, you should try to avoid this. Even more when your tags are generated by a black-box javascript function as yours (with document.write() I guess).
You should try (except very special scenarios) to generate those checkboxes with struts2.
I've been told that the use of scriptlets (<%= ... %>) in my JSP pages isn't such a great idea.
Can someone with a bit more java/jsp experience please give me some pointers as to how to change this code so its more 'best practice', whatever that may be?
This JSP is actually my sitemesh main decorator page. Basically my web design has a tab strip and a submenu, and i wish to somehow highlight the current tab and show the correct submenu by looking at the current request URI.
<%# taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<html>
<head>
<title>My Events - <decorator:title /></title>
<link href="<%= request.getContextPath() %>/assets/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tabs">
<a
<%= request.getRequestURI().contains("/events/") ? "class='selected'" : "" %>
href='<%= request.getContextPath() %>/events/Listing.action'>Events</a>
<a
<%= request.getRequestURI().contains("/people/") ? "class='selected'" : "" %>
href='<%= request.getContextPath() %>/people/Listing.action'>People</a>
</div>
<div class="submenu">
<% if(request.getRequestURI().contains("/events/")) { %>
List of Events
|New Event
<% } %>
<% if(request.getRequestURI().contains("/people/")) { %>
List of People
|New Person
<% } %>
</div>
<div class="body">
<decorator:body />
</div>
</body>
</html>
Thanks all
I think it helps more if you see with your own eyes that it can actually be done entirely without scriptlets.
Here's a 1 on 1 rewrite with help of among others JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) core and functions taglib:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>My Events - <decorator:title /></title>
<link href="${pageContext.request.contextPath}/assets/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tabs">
<a
${fn:contains(pageContext.request.requestURI, '/events/') ? 'class="selected"' : ''}
href="${pageContext.request.contextPath}/events/Listing.action">Events</a>
<a
${fn:contains(pageContext.request.requestURI, '/people/') ? 'class="selected"' : ''}
href="${pageContext.request.contextPath}/people/Listing.action">People</a>
</div>
<div class="submenu">
<c:if test="${fn:contains(pageContext.request.requestURI, '/events/')}">
List of Events
|New Event
</c:if>
<c:if test="${fn:contains(pageContext.request.requestURI, '/people/')}">
List of People
|New Person
</c:if>
</div>
Here's a more optimized rewrite, note that I used c:set to "cache" expression results for reuse and that I use HTML <base> tag to avoid putting the context path in every link (just make all relative URL's in your webpage relative to it --without the leading slash!):
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:set var="isEvents" value="${fn:contains(pageContext.request.requestURI, '/events/')}" />
<c:set var="isPeople" value="${fn:contains(pageContext.request.requestURI, '/people/')}" />
<html>
<head>
<title>My Events - <decorator:title /></title>
<base href="${pageContext.request.contextPath}">
<link href="assets/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tabs">
<a ${isEvents ? 'class="selected"' : ''} href="events/Listing.action">Events</a>
<a ${isPeople ? 'class="selected"' : ''} href="people/Listing.action">People</a>
</div>
<div class="submenu">
<c:if test="${isEvents}">
List of Events|New Event
</c:if>
<c:if test="${isPeople}">
List of People|New Person
</c:if>
</div>
It can actually be optimized more if you collect all those "hardcoded" values like events and people and link texts in a Map in the application scope and use under each the JSTL <c:forEach> to display the tabs.
As to your actual question, you can disable scriptlets (and get runtime errors about using it) by adding the following entry in webapp's web.xml. It may help to spot overseen scriptlets.
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
To learn more about EL, check the Java EE tutorial part II chapter 5. Implicit EL objects, such as ${pageContext} are described here. To learn more about JSTL, check the Java EE tutorial part II chapter 7. Note that JSTL and EL are two separate things. JSTL is a standard taglib and EL just enables to access backend data programmatically. Although it is normally used in taglibs like JSTL, it can also be used standalone in template text.
As an aside, is <%= request.getContextPath() %> an acceptable use of scriptlets that isn't frowned on so much?
This may be an unpopular opinion, but if all you do are simple conditionals and text insertions, I cannot find much fault in the use of scriptlets. (Note the if)
I'd probably use JSTL and the expression language, but mostly because it can be less typing, and IDE support may be better (but a good JSP IDE can also find missing closing brackets and stuff like that).
But fundamentally (as in "keep logic out of templates") I fail to see any difference between
<% if(request.getRequestURI().contains("/events/")) { %>
and
${fn:contains(pageContext.request.requestURI, '/events/')
Scriptlets aren't the worst thing in the world. An important consideration is to think about who is going to be maintaining the code. If its web designers who don't have much Java experience, you are probably better off going with tag libraries. However, if Java developers are doing the maintainance, it may be easier on them to go with scriptlets.
If you end up using a tag library and JSTL, you are expecting the maintainer to also learn the tag library and know JSTL. Some developers will be fine with this as it is a skill they want or already have, but for some developers who only have to deal with JSPs every few months or so, it can be lot less painful to work with clearly written scriptlets written in nice, familiar Java.
This isn't a direct answer to your question (and there are already several good ones, so I won't try to add to it), but you did mention:
Can someone with a bit more java/jsp
experience please give me some
pointers as to how to change this code
so its more 'best practice', whatever
that may be?
In my opinion, best practice, with regards to JSP, is that it should be used strictly as a templating engine, and no more (i.e., no business logic in there). Using JSTL, as many pointed out, definitely helps you get there, but even with JSTL, it's easy to do to much in a JSP.
I personally like to follow the rules laid out in Enforcing Strict Model-View Separation in Templating Engines by the Terence Parr when developing in JSP. The paper mentions the purpose of templating engines (separating model and view), and characteristics of a good templating engine. It takes a good look at JSP and points out ways it's not a good templating engine. Not surprisingly, JSP is basically too powerful and allows developers to do too much. I strongly recommend reading this paper, and it'll help you restrict yourself to the "good" parts of JSP.
If you read only one section in that paper, read chapter 7, which includes the following rules:
the view cannot modify the model either by directly altering model
data objects or by invoking methods on
the model that cause side-effects.
That is, a template can access data
from the model and invoke methods, but
such references must be side-effect
free. This rule arises partially
because data references must be
order-insensitive. See Section 7.1.
the view cannot perform computations upon dependent data
values because the computations may
change in the future and they should
be neatly encapsulated in the model in
any case. For example, the view cannot
compute book sale prices as
“$price*.90”. To be independent of the
model, the view cannot make
assumptions about the meaning of data.
the view cannot compare dependent data values, but can test the
properties of data such as
presence/absence or length of a
multi-valued data value. Tests like
$bloodPressure<120 must be moved to
the model as doctors like to keep
reduc- ing the max systolic pressure
on us. Expressions in the view must be
replaced with a test for presence of a
value simulat- ing a boolean such as
$bloodPressureOk!=null Template output
can be conditional on model data and
com- putations, the conditional just
has to be computed in the model. Even
simple tests that make negative values
red should be computed in the model;
the right level of abstraction is usu-
ally something higher level such as
“department x is losing money.”
the view cannot make data type assumptions. Some type assumptions are
obvious when the view assumes a data
value is a date, for example, but more
subtle type assumptions ap- pear: If a
template assumes $userID is an
integer, the pro- grammer cannot
change this value to be a non-numeric
in the model without breaking the
template. This rule forbids array
indexing such as colorCode[$topic] and
$name[$ID] The view further cannot
call methods with arguments be- cause
(statically or dynamically) there is
an assumed argu- ment type, unless one
could guarantee the model method
merely treated them as objects.
Besides graphics designers are not
programmers; expecting them to invoke
methods and know what to pass is
unrealistic.
data from the model must not contain display or layout information.
The model cannot pass any display
informa- tion to the view disguised as
data values. This includes not passing
the name of a template to apply to
other data values.
Incidentally, Terence has created his own templating engine called String Template which supposedly does a really good job of enforcing these rules. I have no personal experience with it, but would love to check it out on my next project.
You may want to start by using tag libraries. You can use the standard tag library JSTL to do most of the common things that you need scriplets for. There are many other richer tag libraries that are used like in the struts2 framework or from apache.
e.g.
<c:if test="${your condition}">
Your Content
</c:if>
would replace your if statements.
The preferred alternative to scriptlets is the JSTL expression language; here's a good overview. You'll need to add the taglib like so:
<%# taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c' %>
As an example, JSTL provides a bunch of implicit objects that give you the stuff you need; the one you want is pageContext.request.
So you can replace <%request.getRequestURI%> with ${pageContext.request.requestURI}.
You can do conditionals using <c:if> tags.
You'll need to use some web framework. Or at least some convenient taglib. Or a templating enginge like FreeMarker.
Ad frameworks:
If you like JSP way of coding, then I'd suggest Struts 2.
<s:if test="%{false}">
<div>Will Not Be Executed</div>
</s:if>
<s:elseif test="%{true}">
<div>Will Be Executed</div>
</s:elseif>
<s:else>
<div>Will Not Be Executed</div>
</s:else>
Then there's component-oriented JSF.
If you like OOP and coding everything in Java, try Apache Wicket (my favorite) or Google Web Toolkit.