tags:

views:

9021

answers:

5

If you have a JSF (which uses the onclick event of an to submit the current form), how do you execute Javascript (such as asking for delete confirmation) prior to the action being performed?

+2  A: 
<h:commandLink id="myCommandLink" action="#{myPageCode.doDelete}">
 <h:outputText value="#{msgs.deleteText}" />
</h:commandLink>
<script type="text/javascript">
if (document.getElementById) {
 var commandLink = document.getElementById('<c:out value="${myPageCode.myCommandLinkClientId}" />');
 if (commandLink && commandLink.onclick) {
  var commandLinkOnclick = commandLink.onclick;
  commandLink.onclick = function() {
   var result = confirm('Do you really want to <c:out value="${msgs.deleteText}" />?');
   if (result) {
    return commandLinkOnclick();
   }
   return false;
  }
 }
}
</script>

Other Javascript actions (like validating form input etc) could be performed by replacing the call to confirm() with a call to another function.

Grant Wagner
+1  A: 

You can still use onclick. The JSF render kit specification (see Encode Behavior) describes how the link should handle it. Here is the important part (what it renders for onclick):

var a=function(){/*your onclick*/}; var b=function(){/*JSF onclick*/}; return (a()==false) ? false : b();

So your function wont be passed the event object (which isn't reliable cross browser anyway), but returning true/false will short-circuit the submission.

noah
I am not able to add an onclick attribute to <h:commandLink>. I receive the following error: org.apache.jasper.compiler.CompileException: /MyPage.jsp(164,4) Attribute onclick invalid according to the specified TLDI have also seen a number of other people on forums requesting a solution like this.
Grant Wagner
A: 

In JSF 1.2 you can specify onclick events.

Also, other libraries such as MyFaces or IceFaces implement the "onclick" handler.

What you'd need to do then is simply:

<h:commandLink action="#{bean.action}" onclick="if(confirm('Are you sure?')) return false;" />

Note: you can't just do return confirm(...) as this will block the rest of the JavaScript in the onClick event from happening, which would effectively stop your action from happening no matter what the user returned!

Phill Sacre
A: 

If you want to execute something before the form is posted, for confirmation for example, try the form event onSubmit. Something like:

myform.onsubmit = function(){confirm("really really sure?")};
Victor
A: 

This never worked for me,

 onclick="if(confirm('Are you sure?')) return false;" />

but this did

onclick="if(confirm(\"Are you sure?\"))return true; else return false;"
I am not able to add an onclick attribute to <h:commandLink>. I receive the following error: org.apache.jasper.compiler.CompileException: /MyPage.jsp(164,4) Attribute onclick invalid according to the specified TLD I have also seen a number of other people on forums requesting a solution like this.
Grant Wagner