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?
views:
9021answers:
5<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.
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.
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!
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?")};
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;"