Disable a button without changing its appearance - javascript

I implemented a dynamic enable/disable function in a page thanks to a javascript function calling a backing java bean method that sets to true/false a boolean, which is then used to disable (or not) a primefaces commandLink button.
Everything works fine, but I wanted to know if instead of changing the appearance of the button when is it disabled, I could keep the regular appearance (and even better, printing an alert message when trying to click it without having to render another web element).
Here are the simplified pieces of code:
Javascript function:
function enableSubmit(){
jQuery(element).click(function(){
if (condition){
rc_enable();
} else {
rc_disable();
}
});
}
And the primefaces commandButton together with the remoteCommands:
<p:remoteCommand name="rc_disable" update="submitButton" actionListener="#{mappenBean.setDisabled}" />
<p:remoteCommand name="rc_enable" update="submitButton" actionListener="#{mappenBean.setEnabled}" />
<h:commandLink id="submitButton" action="#{mappenBean.updateFund}" styleClass="FormButton" rendered="#{!sitzungBean.gedruckt}" disabled="#{!mappenBean.enabled}">
...[action listeners etc.]
<h:outputText value="Eingaben übernehmen" />
</h:commandLink>
The java bean functions simply set the boolean to true or false.
It seems that I cannot implement a javascript click() function to display an alert if the disabled button is clicked, because once disabled it is not recognized anymore.
The primefaces version is 2.2.1 (i know...) and JSF is 2.1
Any help will be welcome, thanks a lot!

you can add css class to the button to be disabled and disable mouse events
.disabled-button{
pointer-events: none;
}
it wont change the appearance but it will do the trick

You can put a validate function (client side) to check if the condition is true/false and then show the message or submit the action.
First remove the disabled="#{!mappenBean.enabled}"
The button will be always enable. But it will not be submitted if the condition is false.
Add an onclick="return validate();" to your commandLink
Create a javascript function and a dialog for the message.
<script type= "text/javascript">
function validate(){
if(condition){
dialogMessage.show(); // or an alert
return true;
}else{
return false;
}
</script>
Your xhtml will be something like this:
<h:commandLink id="submitButton" action="#{mappenBean.updateFund}" styleClass="FormButton" rendered="#{!sitzungBean.gedruckt}" onclick="return validate();" >
...[action listeners etc.]
<h:outputText value="Eingaben übernehmen" />
</h:commandLink>

I finally managed to do so by adding a click handler on the commandLink with the following code:
onclick="if(#{!mappenBean.enabled}) {alert('test'); return false;}"
However, as Kukeltje pointed out:
But keep in mind that this is a fake and insecure way of disabling. People with a browser developer tool can easily circumvent this. There is a very good and valid reason JSF does all this serverside (never trust the client). It might better be done the other way around. Disable it server side and via css 'enable' it visually and clickable client side!!!
I will keep it running that way for now as it was urgent and I will try and implement the right way of doing it.
Thanks a lot to everyone for your help!

Related

jsf validation before js and js before bean action

JSF / PrimeFaces 3.5
I need when clicking on p:commandButton to check the validation first of all (input text required=true)
if validationFail == false then
Call the popup dialog from js :
else
show requiredMessage from inputText (this field is mandatory...)
I have tried with oncomplete but it calls my bean and after the js popup dialog. I dont want it.
I need in this order : click p:button -> check validation -> if not fails -> show primefaces dialog.
if fails after validation-> render message
My xhtml :
<p:commandButton id="btnSalvar"
value="abc"
action="#{notaFiscalManagedBean.salvar}"
oncomplete="if (args.validationFailed) return true; else return showPF_DiagBox()"
in my showPF dialog I call bean method. if OK clicked by user.
It is better to user RequestContext of primefaces which allows user to execute javascript which is set from managed bean. You can use it by modifying your method at #{notaFiscalManagedBean.salvar} as shown below.
public String salvar(){
boolean valid=true;
//Do your validation here
if(valid){
RequestContext.getCurrentInstance().execute("showPF_DiagBox()");
}
}
If you want to do the validation on client side before submitting the request to the server then just do the following change in your code,
<p:commandButton id="btnSalvar"
value="abc"
action="#{notaFiscalManagedBean.salvar}"
onclick="if(validationFailed()){return false}"
oncomplete="showPF_DiagBox()"/>
Also write down a javascript function to do validations
function validationFailed(){
//Check various conditions based on component validations and return whether validatoin failed or not
}
Try this:
<p:commandButton id="btnSalvar"
value="abc"
action="#{notaFiscalManagedBean.salvar}"
update="#form"
render="#form"/>
By adding 'render' and 'update' attributed your form will have to reload, and then process all the validations inside of it's form.
Hope this can help you, good luck!
In my oncomplete commandButton I got what I wanted getting from #BalusC answer (How to find indication of a Validation error (required="true") while doing ajax command) and #Tuukka Mustonen (JSF 2.0 AJAX: Call a bean method from javascript with jsf.ajax.request (or some other way)) and making some adjustments to fit my needs.
This way, if there are any validation errors or any converters do be validated, they are rendered at screen first of all. If there are not validation errors so I execute my js function and inside it I fire my bean method if needed.
thanks for everybody ! :)

Back button needs to redirect to last visited page

In web site I have to add "Back" button or Link URL which will redirects to me previously visited page.
Currently I have added below code, but it doesn't always work.
<i>Back</i>
I observed that it is not working in Google chrome.
<script>
function sample(){
window.location.href = window.history.back(1);
}
</script>
<input type="button" value="trying" onclick="sample()"/>
I have tested here it is working test ... :)
Event this work as same
<i>Back</i>
Try this :
<input action="action" type="button" value="Back" onclick="history.go(-1);" />
The following was an incorrect assumption by me
The value passed to onclick should be a function to call when the link is clicked. You are passing window.history.back() which is the value returned by the back function.
Try the following.
<i>Back</i>
Turns out I assumed, incorrectly, that the value of onClick should be a function to call on click. As Brian North and putvande pointed out in the comments it should be the javascript code to run when the event is triggered.
Suggestion
However one should generally avoid binding events in the way you are doing as it couples presentation, HTML, too tightly with the javascript. Instead one should bind the click listener from an external javascript file using for example addEventListener or jQuery.on.
jQuery example
HTML
Back
Javascript
$(function() {
$("#history-back").on("click", window.history.back);
});

Stop page reload of an ASP.NET button

NET application, I have inserted a button that call a Javascript function (OnClientClick event) and a VB.NET function (OnClick event)
<asp:Button OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
The problem is that when I click the button, it refreshes the page and delete the content of the text boxes.
I have tried with inserting return false; on the OnClienClick event, but it doesn't execute the OnClick Event.
How can I avoid the page reload ?
P.S.: At the end of the Javascript function a new window is opened window.open(newWindow.aspx), but I want that the first page mantain the value inserted by the user in the Text Boxes.
Thanks in advance :)
You need to use return statement at two points.
OnClientClick="return jsfunction();"
function jsfunction()
{
//
return false;
}
OR, you can return false after the function call like this.
OnClientClick="jsfunction(); return false;"
Note if you want to do postback conditionally then you need to return true or false.
OnClientClick="return jsfunction();"
function jsfunction()
{
if(conditionForPostBack)
return true;
else
return false;
}
or you can disable the submit behaviour. By default asp.net renders button as submit button. if you disable submit behaviour it will render button as button type
<asp:Button UseSubmitBehavior="false" OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
But with this code it will not fire server side event "OnClick"
if you are not going to trigger the button with C# Codebehind function, then you dont need to use asp:Button. Therefore you can use a regular html .
<button id='btn_1' onclick='ajax_function()'>Button</button>
html button is much easier and faster. if you use asp:button, then you should use clientid() function to catch the control to trigger the ajax.
Searching for the same thing as you i find a patch:
If you call a method server side, you can use AJAX with the update panel, but that didn't worked for me. But you can save what you want in Session, so you have it as far as Session lasts.
// Save at SessionParameter the elementToSave we want.
this.Session["SessionParameter"] = elementToSave;
// Retrieve the info from the Session
ElementYouNeededToSave = (TypeOfTheElement)Session["SessionParameter"];
Hope this will help someone in my situation.

javascript confirm asp.net button never submits?

i have a regular asp:button. I am working in .Net 3.5. I've tried adding a js confirm to the button with the OnClientClick attribute as well as adding in code-behind and the result is the same. No matter what the user clicks in the confirm pop-up the form will not submit??
BtnDeleteSelected.Attributes.Add("onclick", "return confirm('Are you sure you want to delete?');");
The confirm dialog appears and if i select "OK" it still does not submit.. Any ideas? thanks.
That's because you should not be returning in all cases. If you view the source of the page and look for the button markup, you are likely to see this...
onclick="return confirm('Ok?'); __doPostback();"
The __doPostback invocation is inserted automatically by the ASP.NET framework in some cases. Since you return immediately regardless of the result of confirm, the postback never fires. The ultimate solution would be to not to set the onclick attribute, but instead use an unobtrusive approach. However, if there is pressing reason to control this on the server-side via onclick, you can use a simple if statement and only return when they press "Cancel"...
string js = "if(!confirm('Are you sure you want to delete?')) return false;";
BtnDeleteSelected.Attributes.Add("onclick", js);
I had this problem too. I was using adding the client side javascript in the OnItemCreated code of a datagrid like this:
myTableCell = e.Item.Cells(iDeleteColumnNumber) 'Delete Button Column
myDeleteButton = myTableCell.Controls(1)
If myDeleteButton.UniqueID = "lbtnDelete" Then
myDeleteButton.Attributes.Add("onclick", "if(!confirm('OK to Delete?'))return false;")
End If
For some reason that didn't work. I then moved the JavaScript to the <asp:linkbutton> in the design view like this:
<asp:LinkButton id="lbtnDelete" runat="server" CssClass="link-text" Text="<img border=0 src=../images/icons/icon-delete.gif alt=Delete>"
CommandName="Delete" CausesValidation="false" OnClientClick="if(!confirm('OK to Delete?'))return false;"></asp:LinkButton>
And that worked for me.
Do you have to return TRUE if validation passes? Meaning, if confirm() returns false I don't think the form will submit.
Your code looks OK on the surface. Do you have any validators that might be preventing it being submitted? Try adding BtnDeleteSelected.CausesValidation = false to prevent the delete button calling any client-side validators.
Please try calling doPostBack function ;)
I mean:
BtnDeleteSelected.Attributes.Add("onclick", "CheckConfirm();");
<script language="javascript">
function CheckConfirm()
{
if ( confirm('Are you sure you want to delete?') )
__doPostBack('BtnDeleteSelected','');
else
return false;
return true;
}
</script>
Hope that helps,

ASP.NET postback with JavaScript

I have several small divs which are utilizing jQuery draggable. These divs are placed in an UpdatePanel, and on dragstop I use the _doPostBack() JavaScript function, where I extract necessary information from the page's form.
My problem is that when I call this function, the whole page is re-loaded, but I only want the update panel to be re-loaded.
Here is a complete solution
Entire form tag of the asp.net page
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>
<input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
<input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />
<asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
<asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>
Entire Contents of the Page's Code-Behind Class
Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
Response.Write("You ran the ButtonA click event")
End Sub
Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
Response.Write("You ran the ButtonB click event")
End Sub
The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed
What's going on?
Two input controls are rendered to the client:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
__EVENTTARGET receives argument 1 of __doPostBack
__EVENTARGUMENT receives argument 2 of __doPostBack
The __doPostBack function is rendered out like this:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
As you can see, it assigns the values to the hidden inputs.
When the form submits / postback occurs:
If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (javascript:__doPostBack('ButtonB',''), then the button click handler for that button will be run.
What if I don't want to run a click handler, but want to do something else instead?
You can pass whatever you want as arguments to __doPostBack
You can then analyze the hidden input values and run specific code accordingly:
If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
Response.Write("Do Something else")
End If
Other Notes
What if I don't know the ID of the control whose click handler I want to run?
If it is not acceptable to set ClientIDMode="Static", then you can do something like this: __doPostBack('<%= myclientid.UniqueID %>', '').
Or: __doPostBack('<%= MYBUTTON.UniqueID %>','')
This will inject the unique id of the control into the javascript, should you wish it
Per Phairoh: Use this in the Page/Component just in case the panel name changes
<script type="text/javascript">
<!--
//must be global to be called by ExternalInterface
function JSFunction() {
__doPostBack('<%= myUpdatePanel.ClientID %>', '');
}
-->
</script>
Using __doPostBack directly is sooooo the 2000s. Anybody coding WebForms in 2018 uses GetPostBackEventReference
(More seriously though, adding this as an answer for completeness. Using the __doPostBack directly is bad practice (single underscore prefix typically indicates a private member and double indicates a more universal private member), though it probably won't change or become obsolete at this point. We have a fully supported mechanism in ClientScriptManager.GetPostBackEventReference.)
Assuming your btnRefresh is inside our UpdatePanel and causes a postback, you can use GetPostBackEventReference like this (inspiration):
function RefreshGrid() {
<%= ClientScript.GetPostBackEventReference(btnRefresh, String.Empty) %>;
}
While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.
__doPostBack('myUpdatePanelId','')
*note: second parameter is for addition event args
hope this helps someone!
EDIT: so it seems this same piece of advice was given above as i was typing :)
If anyone's having trouble with this (as I was), you can get the postback code for a button by adding the UseSubmitBehavior="false" attribute to it. If you examine the rendered source of the button, you'll see the exact javascript you need to execute. In my case it was using the name of the button rather than the id.
Have you tried passing the Update panel's client id to the __doPostBack function? My team has done this to refresh an update panel and as far as I know it worked.
__doPostBack(UpdatePanelClientID, '**Some String**');
First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.
Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.
This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.
You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

Categories