Javascript calculator in JSF view calling server side - jsf

I need to make a calculator in a jsf view using only client-side part. No data can be passed to server-side.
I have the view splitted in a couple of <h:form> with calculator in the middle:
<h:form id="customer_form">
// view here working nice
</h:form>
<h:panelGroup layout="block" styleClass="ui-grid-col-2 offset-boxes" >
<p:panel id="calculator" header="Calculadora" styleClass="half-screen-height calculator-table">
<h:inputText id="result" widgetVar="result" styleClass="result-text"/>
<p:button value="X" widgetVar="X" ajax="false" onclick="calculate('x')" styleClass="right"></p:button>
// more calculator buttons
</p:panel>
</h:panelGroup>
<h:form id="consumption_form">
// view here working nice
</h:form>
Until here all is ok, but when I try to manage calculator with javascript:
<script type="text/javascript">
function calculate(sel){
if (sel == "x") {
document.getElementById("result").value = "";
} else {
var input = document.getElementById("result").value;
document.getElementById("result").setAttribute("value", input + sel);
}
}
</script>
Each time i change result value, server-side is called and value is reset to original value.
EDIT according to PrimeFaces documentation of p:button::onclick event
Client side callback to execute when button is clicked.
Either <h:button> tag is acting like this, so I guess problem is the way JSF or PrimeFaces are handling the javascript event...
I also tried to call and set input value by jquery with $("result").value but the result i get is a function(b7) not the value itself.
What am I doing wrong?
Thanks! ;)
J

you got to make sure you're JS code will not try to submit the form, so that will trigger a server side call, for that I suggest you return false and try using event.preventDefault() on your HTML buttons onclick calls, so you will avoid bubbling up the event to any listeners.

Related

Primefaces blockUi trigger by boolean value

How to trigger primefaces <p:blockUI> using boolean in backing bean? In this showcase, it requires a commandButton to trigger the the blockUI. What I want is block some part of the page base on a boolean in the backing bean. Is this possible? I tried setting the rendered attribute in the <p:blockUI> tag but it still won't work.
Here is my code:
<p:blockUI block="grid" rendered="#{bean.trueValue}"></p:blockUI>
<p:panelGrid id="grid">
-- content
</p:panelGrid>
One way is to call hide() and show() method of BlockUI from Managed Bean.
You can do that by using RequestContext:
RequestContext.getCurrentInstance().execute("widgetVar.show()");
Another is you can pass the variable to JavaScript function and then let the Javascript function take care of that for you.
onClick="func(#{elvariable})"
<script type="text/javascript">
function func(value)
{
if(value==something){
widgetVar.show();
}else{
widgetVar.hide();
}
}

Call an action listener via ajax when user presses enter on a h:form input field

I have this form
<h:form id="formId" prependId="false">
Descrizione <h:inputTextvalue="#{bean.description}" />
Prezzo: <h:inputText value="#{optionalManaged.price}" />
<a4j:commandLink styleClass="button smallButton" actionListener="#{bean.method}"
execute="formId" render="otherDiv">
+
</a4j:commandLink>
</h:form>
At the moment, pressing the a4j:commandLink stores the two input filelds' values inside my bean and calls my action listener correctly.
What I'd like to happen is that pressing enter on the second inputText does the same.
I made a naive try by calling the a4j:commandLink click() via jquery from inside the inputText. This, obviously, didn't work.
Any idea on how I could do this?
You need to detect if Enter key was pressed and click the command link programmatically. Just don't forget to set its id, as well as id of input component. The piece of JavaScript you need to add when the page has finished loading is:
document.getElementById('input').onkeypress = function(e) {
var event = e || window.event;
var code = event.which || event.keyCode;
if (code == 13) {
document.getElementById('link').click();
return false;
}
}

How to autosubmit a form in jsf

I am trying to autosubmit a jsf form.
I have one inputhidden textbox in the form, where the field value is set from request object.Once its done, the form need to submit automatically.
I have done autosubmit using javascript and also using Primefaces, but I need to do it using Simple JSF stuff.
No need of using richfaces, primefaces.
<h:form id="form">
<h:inputhidden value="#ManagedBean.user"/>
<h:comandbutton action="#{ManagedBean.processAction()}" /> //disabled
</h:form>
if you use jquery, you can add an event listener to the form and check if enter is pressed.
We do this following way with richfaces, but it maps quite simple to jquery:
<rich:hotKey
selector="#searchForm"
key="return"
type="keypress"
handler="if (isValidInputFieldForHotkeyEvent(event)) { event.preventDefault(); jQuery('.searchFormDefaultAction').click(); } else { sendShiftEnter(event); }"
disableInInput="false"
disableInInputTypes=""/>
These are the javascript functions:
function isValidInputFieldForHotkeyEvent(event) {
return event.target.type != 'textarea';
}
function sendShiftEnter(event) {
event.shiftKey = true;
event.ctrlKey = true;
event.altKey = true;
event.keyCode = 13;
event.target.fireEvent("keyPressed", event);
}
You can use plain old javascript? On window load call
document.getElementById('form').submit();

calling a Javascript function that makes a click on a (hidden) button or link

I call a javascript function that makes a click on a hidden commandButton but the click run when the page loads, not when I call the function.
this is the html code :
<p:inputText id="aa" value="#{bonBonneManagedBean.sel}" onkeyup="fnc()" />
<h:commandButton id="hh" onclick="#{bonBonneManagedBean.kk()}" style="display:none"/>
and the javaScript function :
function fnc()
{
length = document.getElementById('form:aa').value.length;
if(length == 10)
{
$("#hh").click();
document.getElementById('form:aa').value = "";
}
}
You should use the action attribute instead of onclick like this
<h:commandButton id="hh" action="#{bonBonneManagedBean.kk()}" style="display:none"/>
Note that you might have to add form prefix to the selector, like this
$("#myFormId\\:hh").click();
The same would work for a commandLink or any other 'clickable' component.
Must there be a button on this page(which I doubt, seeing as you're hiding it anyways)? You're better served using something like <p:remoteCommand/> here
Ditch the hidden button and replace with
<p:remoteCommand name="fnc" actionListener="#{bonBonneManagedBean.kk}"/>
But, if it's an absolute requirement, you can very easily emulate a button click in js with the click() method from your function you need to
Change the <h:commandButton/> to a <p:commandButton/> so you can assign the button a widgetVar attribute(to guarantee the name of the element in the DOM). The widgtetVar attribute can be set on almost all primefaces components to make your life easier
Using the widgetVar, just call the click() method in your function
<p:commandButton ajax="false" widgetVar="theButton" id="hh" action="#{bonBonneManagedBean.kk()}" style="display:none"/>
<p:inputText id="aa" widgetVar="theTextBox" value="#{bonBonneManagedBean.sel}" onkeyup="fnc()" />
and in the function:
function fnc(){
length = theTextBox.value.length;
if(length == 10){
theButton.click()
theTextBox.value = "";
}
}
If the top answers from Daniel and Kolossus doesn't help out someone: I found that characters got put in front of the id I set in my case, therefore this helped me:
$('[id$=hh]').click();
Basically the selector is saying the id ends with 'hh' but may not be the full id.
This is also helpful in SF development as the same thing happens with comandButtons, etc.

How to do double-click prevention in JSF

We have a few search pages that run against a lot of data and take a while to complete. When a user clicks on the search button, we'd like to not allow them to submit the search result a second time.
Is there a best practice for doing "double-click" detection/prevention in JSF?
The PrimeFaces component seems like it can do what we want as it will disable the UI for a period of time between when the search button is clicked and when the search completes, but is there a more generic strategy we can use (perhaps something that isnt reliant on PrimeFaces)? Ideally, any click of the button will either be disabled or disregarded until the search completes. We dont necessarily need to disable the entire UI (as blockUI allows you to do).
If you're using solely ajax requests, you could use jsf.ajax.addOnEvent handler of the JSF JavaScript API for this. The below example will apply on all buttons of type="submit".
function handleDisableButton(data) {
if (data.source.type != "submit") {
return;
}
switch (data.status) {
case "begin":
data.source.disabled = true;
break;
case "complete":
data.source.disabled = false;
break;
}
}
jsf.ajax.addOnEvent(handleDisableButton);
Alternatively, if you need this on specific buttons only, use the onevent attribute of <f:ajax>.
<h:commandButton ...>
<f:ajax ... onevent="handleDisableButton" />
</h:commandButton>
If you also need to apply this on synchronous requests, then you need to take into account that when you disable a button during onclick, then the button's name=value pair won't be sent as request parameter and hence JSF won't be able to identify the action and invoke it. You should thus only disable it after the POST request has been sent by the browser. There is no DOM event handler for this, you'd need to use the setTimeout() hack which disables the button ~50ms after click.
<h:commandButton ... onclick="setTimeout('document.getElementById(\'' + this.id + '\').disabled=true;', 50);" />
This is only rather brittle. It might be too short on slow clients. You'd need to increase the timeout or head to another solution.
That said, keep in mind that this only prevents double submits when submitting by a web page. This does not prevent double submits by programmatic HTTP clients like URLConnection, Apache HttpClient, Jsoup, etc. If you want to enforce uniqueness in the data model, then you should not be preventing double submits, but preventing double inserts. This can in SQL easily be achieved by putting an UNIQUE constraint on the column(s) of interest.
See also:
Pure Java/JSF implementation for double submit prevention
How to handle multiple submits before response is rendered?
You can use 'onclick' and 'oncomplete' listeners. When user click on button - disable it. When action completed - enable.
<p:commandButton id="saveBtn"
onclick="$('#saveBtn').attr('disabled',true);"
oncomplete="$('#saveBtn').attr('disabled',false);"
actionListener="#{myBean.save}" />
i came upon this question, having the same problem. The solution did not work for me - after a brief look at primefaces.js i guess they do not use jsf.ajax there anymore.
so i had to work something out myself and here is my solution, for people who also can not use the one in the answer by BalusC:
// we override the default send function of
// primeFaces here, so we can disable a button after a click
// and enable it again after
var primeFacesOriginalSendFunction = PrimeFaces.ajax.AjaxUtils.send;
PrimeFaces.ajax.AjaxUtils.send = function(cfg){
var callSource = '';
// if not string, the caller is a process - in this case we do not interfere
if(typeof(cfg.source) == 'string') {
callSource = jQuery('#' + cfg.source);
callSource.attr('disabled', 'disabled');
}
// in each case call original send
primeFacesOriginalSendFunction(cfg);
// if we disabled the button - enable it again
if(callSource != '') {
callSource.attr('disabled', 'enabled');
}
};
None of alternatives above has worked for me (I've really tried each one of them). My form was always sent twice when user double-clicked the login button. I'm working with JSF (Mojarra 2.1.6) on Glassfish 3.1.2.
Consider that it was a non-AJAX login page.
So here's the way I solved it:
define a global JavaScript var to control submition in the page header or anywhere outside your form:
var submitting = false;
set it to true when submit h:form onsubmit event is fired:
<h:form onsubmit="submitting = true">
Check the var's value on h:commandLink's click event:
<h:commandLink ... onclick="if(submitting){return false}">
This is just another simple alternative and it was tested in Chrome [Version 47.0.2526.106 (64-bit)], Mozilla Firefox (37.0.2) and Internet Explorer 11. I hope it helps someone.
For me works this way:
<h:commandLink ... onclick="jQuery(this).addClass('ui-state-disabled')">
PrimeFaces 12 and up
From PrimeFaces 12, p:commandButtons are disabled by default when they trigger an Ajax request. The button is enabled again when the Ajax request is finished.
To disable this default behavior, use disableOnAjax="false".
See a demo at: https://www.primefaces.org/showcase/ui/button/commandButton.xhtml
PrimeFaces 11 and lower
The approach by BalusC is great, but if you are using PrimeFaces you'll run into styling issues. Because some classes are not toggled, the button will not look disabled.
If you are looking for a solution which takes care of styling as well, you can replace the CommandButtonRenderer with one that disables the button on click using the button's widget to disable and enable it.
PrimeFaces Extensions 8 or up contains such a renderer. You can add this to your faces-config.xml like:
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.CommandButtonRenderer</renderer-type>
<renderer-class>org.primefaces.extensions.renderer.CommandButtonSingleClickRenderer</renderer-class>
</renderer>
</render-kit>
You can see it in action in the showcase.
If you cannot or don't want to use PFE, you can add the render class to your project by getting it from:
https://github.com/primefaces-extensions/primefaces-extensions/blob/master/core/src/main/java/org/primefaces/extensions/renderer/CommandButtonSingleClickRenderer.java
Note: this still requires you to add the renderer to your faces-config.xml.
See also
How to use resolveWidgetVar before PrimeFaces 8?
very useful solution jsf-primefaces, used with facelets template spreads to other pages consumers
<f:view>
<Script language="javascript">
function checkKeyCode(evt)
{
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if(event.keyCode==116)
{
evt.keyCode=0;
return false
}
}
document.onkeydown=checkKeyCode;
function handleDisableButton(data) {
if (data.source.type != "submit") {
return;
}
switch (data.status) {
case "begin":
data.source.disabled = true;
break;
case "complete":
data.source.disabled = false;
break;
}
}
jsf.ajax.addOnEvent(handleDisableButton);
</Script>
</f:view>
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="./resources/css/default.css" rel="stylesheet" type="text/css" />
<link href="./resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
<title>infoColegios - Bienvenido al Sistema de Administracion</title>
</h:head>
<h:body onload="#{login.validaDatos(e)}">
<p:layout fullPage="true">
<p:layoutUnit position="north" size="120" resizable="false" closable="false" collapsible="false">
<p:graphicImage value="./resources/images/descarga.jpg" title="imagen"/>
<h:outputText value="InfoColegios - Bienvenido al Sistema de Administracion" style="font-size: large; color: #045491; font-weight: bold"></h:outputText>
</p:layoutUnit>
<p:layoutUnit position="west" size="175" header="Nuestra InstituciĆ³n" collapsible="true" effect="drop" effectSpeed="">
<p:menu>
<p:submenu>
<p:menuitem value="Quienes Somos" url="http://www.primefaces.org/showcase-labs/ui/home.jsf" />
</p:submenu>
</p:menu>
</p:layoutUnit>
<p:layoutUnit position="center">
<ui:insert name="content">Content</ui:insert>
</p:layoutUnit>
</p:layout>
</h:body>
Did a simple work with hide and show, works well with element having input type submit Jquery
$(":submit").click(function (event) {
// add exception to class skipDisable
if (!$(this).hasClass("skipDisable")) {
$(this).hide();
$(this).after("<input type='submit' value='"+$(this).val()+"' disabled='disabled'/>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<form>
<input type="submit" value="hello">
</form>
I addressed this issue by simply hiding the button after clicking it:
<p:commandButton... onclick="jQuery(this).css('visibility','hidden')" />

Resources