The real question: I'm trying to understand the interaction between a javascript snippet I found and the Primefaces commandButton. The javascript snippet is assigned to the onkeypress attribute of the JSF h:form tag. I have this snippet working on some of my pages but not on others. When I tried to strip down the non-essentials to ask THAT question the javascript stopped working entirely.
There seems to be something I don't understand since this code doesn't work. Note the code does work if the user actually clicks the button. I want it to work when they press the Enter key. I have stripped away as much as I can and lobotomized style guidelines to make it shorter.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Tray Report</title>
<h:outputStylesheet library="css" name="postalreports.css" />
</h:head>
<h:body>
<h:form id="thisform" onkeypress="if (event.keyCode == 13) { document.getElementById('thisform:btn').click(); return false; }" >
<p:panel id="panel" header="Report For Days">
<p:messages id="messages" />
<p:inputText id ="days" value="#{trayBean.days}" >
</p:inputText>
</p:panel>
<p:commandButton id="btn" value="RUN" actionListener="#{trayBean.run}"/>
</h:form>
</h:body>
</html>
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewScoped
public class TrayBean implements Serializable {
private Integer days = 1;
public TrayBean() {}
public void run() {
System.out.println("do something here");
}
public Integer getDays() { return days; }
public void setDays(Integer days) { this.days = days; }
}
P.S. I also tried if (event.keyCode == 13) { this.submit(); }
ADDED AFTER ADDITIONAL RESEARCH: Much to my chagrin, I have found a Primefaces specific solution to this that I should have found earlier. It turns out that no JavaScript is needed at all with the simple addition of the p:focus tag. Here is the XHTML file that actually works. There is no change to the backing bean.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Tray Report</title>
</h:head>
<h:body>
<h:form id="thisform">
<p:focus/>
<p:panel id="panel" header="Report For Days">
<p:messages id="messages" />
<p:inputText id ="days" value="#{trayBean.days}" >
</p:inputText>
</p:panel>
<p:commandButton id="btn" value="RUN" actionListener="#{trayBean.run}"/>
</h:form>
</h:body>
</html>
This will allow me to complete the analysis of my original problem (since I have a p:focus tag on pages that don't work yet) which I will post separately.