2

I am trying to submit a spring form based on confirm condition using java script. following is my Controller

@RequestMapping("/loadPage.do")
public ModelAndView loadPage()
{
    ModelAndView modelAndView;
    //some code
    return modelAndView;
}
@RequestMapping(value="/submitAction.do" , method=RequestMethod.POST)
public String submitForm(@ModelAttribute Object form, Model m ){
    //some code
    return "page";
}

JSP

<script>
    function confirmForChanges (){
        var r= confirm("Do you want to proceed");
        if (r == true) {
            document.getElementById('submitButton').action = "/root/submitAction.do";
            document.getElementById('submitButton').submit();
            alert("Your changes have been saved");
        }if (r ==false){
            alert("changes not saved")
        }
    }
</script>

<form:form  action="/submitAction.do" commandName="command" method="post">
<input id=cancelButton type="button" value="Cancel" />
<input id=submitButton type="submit" value="Submit" onclick="javascript:confirmForChanges();"/>;
</form:form>

The problem is even if i do a cancel, the form gets submitted :( I tried removing the action="/submitAction.do" from the form in jsp but no luck.

1 Answer 1

5

Try using the event onsubmit="return confirmForChanges();"

function confirmForChanges() {
  var save = confirm("Do you want to proceed");
  alert(save ? 'Your changes have been saved' : 'changes not saved');
  return save; //if true then submit else don't submit
}
<form:form action="/submitAction.do" commandName="command" method="post" onsubmit="return confirmForChanges();">
  <input id=cancelButton type="button" value="Cancel" />
  <input id=submitButton type="submit" value="Submit" />
</form:form>

Sign up to request clarification or add additional context in comments.

1 Comment

this solution is working with onclick and not with onsubmit, in case of onsubmit it goes to the controller and submits the form, then to the script. But return with onclick really did work :) Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.