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,
Related
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!
I apologize if this has been answered somewhere but I could not find my particular problem's answer.
I have a asp object:
<asp:CheckBox ID="chkRemove" runat="server" Checked='<%#Convert.ToBoolean(Eval("CommonWord")) %>' OnCheckedChanged
= "OnCheckedChanged_CommonWord" AutoPostBack="true" />
Basically I want to show a message box asking if its ok to remove, if no or cancel is selected, don't do a postback (or don't run any server side code), and if yes then run that function "OnCheckedChanged_CommonWord".
I tried doing a javascript Confirm() call which pops up but if I press yes, the C# server side code does not run ("OnCheckedChanged_CommonWord") the "no" or "cancel" works perfectly as it doesn't do a postback.
P.s. Please no AJAX due to server restrictions for me.
The Checkbox control actually lacks any type of OnClientCheckChanged event that can be used to manage if a PostBack should occur or not (like OnClientClick, etc.) based on a client-side event.
But you should be able to accomplish this using an onclick attribute with a function to manage the default PostBack by calling it manually :
<asp:CheckBox ID="chkRemove" runat="server"
Checked='<%#Convert.ToBoolean(Eval("CommonWord")) %>'
OnCheckedChanged="OnCheckedChanged_CommonWord"
AutoPostBack="true"
onclick='return OnClientCheckChanged("Are you sure you want to do this?",this);' />
<script>
function OnClientCheckChanged(prompt,source) {
if (confirm(prompt)){
__doPostBack("'" + source.id + "'", '');
return true;
}
else {
return false;
}
}
</script>
When the CheckBox is actually clicked, it will trigger your confirm() prompt and based on the result, it will either trigger an explicit PostBack (via the nasty __doPostBack() call or it won't do anything.
I'm not a huge fan of the __doPostBack() call, but it seems like an appropriate solution here.
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 ! :)
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.
It looks like the Internet Explorer demon has struck again, and I cannot seem to figure this one out:
I have an ImageButton using OnCommand to delete a specific entry from my database. I however have implemented it so that the user will first confirm that they want to delete a specific item.
Here is the code for my ImageButton
<asp:ImageButton runat="server" ID="imgDelete" ImageUrl="~/Controls/TaskDetails/Images/delete.png" OnCommand="Tag_DeleteCommand" Visible='<%# CanDelete %>' OnClientClick="javascript:confirmDialog(this, 'Remove Tag','Are you sure you want to remove this tag?', 1); return false;"
CommandArgument='<%# Eval("TagID") %>' />
And here is my ConfirmDialog function
function confirmDialog(sender, title, message, type) {
//type entities
//1 = warning
//2 = error
//3 = success
//4 = Information
var sender = $(sender);
$("#message_dialog_inner_text").html(message);
$("#message_dialog_message_container").dialog({
modal: true,
title: title,
zIndex: 10003,
dialogClass: (type > 0) ? "message_dialog_type_" + type : "",
position: 'center',
buttons: {
"OK": function () {
//the yes option was selected, we now disable the onclientclick event, and fire the click event.
$(this).dialog("close");
if (sender.hasAttr("href")) {
window.location = sender.attr('href');
} else {
sender.removeAttr("onclick");
sender.trigger("click");
}
},
"Cancel": function () { $(this).dialog("close"); }
}
});
return false;
}
This works fine in Chrome, FF, Safari, but IE is just ignoring it and doing the postback. I have even changed my OnClientClick to "return false;" and it seems to have no impact on the button posting back. I have also changed it from an ImageButton to just a Button, to no avail. I am assuming it has something to do with the OnCommand event, but right I am at a loss! I have implemented this througout a pretty huge application, so I would like to manage the scope of the change. If anyone has some input, it would be greatly appreciated!
EDIT
OK, let me also just stress, I don't want it to post back, and even if I just have OnClientClick="return false;" the command button is still posting back (not what you would expect).
Here is the rendered markup from my ImageButton control
<input type="image" name="ctl00$body$pnlContentRight$pnlCurrentTaskDetails$repTags$ctl00$tagItem$imgDelete" id="ctl00_body_pnlContentRight_pnlCurrentTaskDetails_repTags_ctl00_tagItem_imgDelete" src="Controls/TaskDetails/Images/delete.png" onclick="javascript:confirmDialog(this, 'Remove Tag','Are you sure you want to remove this tag?', 1); return false;" style="border-width:0px;">
This isn't a resolution to your specific issue, but it's a workaround you may want to consider (I've used it in a couple of places):
Make your "delete" button a simple image, not a postback button.
Give it an OnClientClick which calls a local javascript function (passing the relevant data - at a minimum, the ID of the item to be deleted).
That local JS function loads the relevant data into a hidden var (so it can be accessed in your code-behind), and opens the jQuery confirm dialog.
That dialog is configured with NO jquery-dialog buttons. Instead, the launched DIV contains two asp:Buttons: ok and cancel. The cancel button simply closes the jQuery dialog. The OK button is a normal postback button with a server-side OnClick function.
Thus, the page is only posted-back if the user clicks the OK button on the confirm dialog. The confirm-dialog-event function knows which item to delete because that item's ID is in the hidden field.
This is probably not the "right" way to implement this behavior (from an ASP.NET purist standpoint). However, as workarounds go, I don't think it's too painfully kuldgey. And in my experience, it seems to work across all browsers (assuming they have JS enabled, of course). HTH.
You're OnClientClick is always returning false, which means that the event will never be executed. Try returning the input from the confirm like this:
OnClientClick="return confirmDialog(...);"
You will need to make sure that there is a way to return true from the confirmDialog function too. It looks like that function always returns false too.
I'm not very familiar with the jQuery UI dialog, but in concept it should work like this:
buttons: {
"OK": function () { return true; }, //perform a postback and execute command
"Cancel": function () { return false; } //abort postback and do nothing
}