JSP Two submit buttons on one page and one form

Hi,
I have two buttons on one page and one form. On click of one button, ‘Button 1’, I need to get the form data and validate and then based on a condition display the remaining div and other button ‘Button 2’ . On click of Button 2 again, I need to take all the data and submit again.

JSP:

<template:page pageTitle="${pageTitle}">
<div class="get-started page">
<insurance:insuranceProgress percentage="33" />
  <div class="container">
    <header>
      <h1><spring:theme code="insurance.startRecharge" /></h1>
    </header>
    <div class="row">
      <div class="col-sm-8">
        <div class="panel">
          <div class="panel-body">
            <div class="row">
              <div class="col-sm-12">
                <p>
                 <spring:theme code="insurance.insuranceCompany" />
                  <span class="text-primary"><spring:theme code="insurance.note" /></span>
                </p>
              </div>
            </div>
          </div>
        </div>
<c:url var="actionUrl" value="/insurance/submit" />
 <form:form method="post" class="brand-form" commandName="insuranceForm"
	action="${actionUrl}" id="insuranceForm">
           <div class="row">
            <div class="col-sm-7">
              <div class="panel">
                <div class="panel-body with-border-bottom">
                  <h2><spring:theme code="insurance.validateNumber" /></h2>
                  <p><spring:theme code="insurance.enterMobileNumber" /></p>
                </div>
                <div class="row row-no-space">
                  <div class="col-sm-12 form-group with-button">
                   	<formElement:formInputBox idKey="mobileNumber" type="tel" labelKey="insurance.mobileNumber" 
                   		path="mobileNumber" inputCSS="text" " 
                   		mandatory="true" />
                   	<form:button type="button" class="btn btn-default" onClick="location.href='/insurance'"><spring:theme code="insurance.edit" />
                   	</form:button>
                  </div>
                </div>
              </div>
              <button type="submit" class="btn btn-primary-dark before-panel-margin">Button 1</button>
            </div>
          </div>

          <div class="panel">
            <div class="panel-body">
              <h2><spring:theme code="insurance.selectPayment" /></h2>
              <p><spring:theme code="insurance.voucherOrCC" /></p>
              <div class="btn-group btn-block">
                <button type="button" class="btn btn-primary btn-half" id="creditCardBtn">
                <spring:theme code="insurance.creditCardBtn" />  
                </button>
                <button type="button" class="btn btn-default btn-half" id="debitCardBtn">
                <spring:theme code="insurance.debitCardBtn" />
                </button>
                <form:hidden path="insuranceOption" value="CREDITCARD" />
              </div>
            </div>
          </div>
  			 <button type="submit" class="btn btn-primary-dark"> Button 2
          <span class="glyphicon glyphicon-menu-right"></span>
        </button>
        </form:form>
      </div>
    </div>
  </div>
</div>
</template:page>

When page loads only data till Button 1 should be visible. On click of Button 1, based on back end logic, i ll pass true or false. If true, then remaining data should also be visible. Onclick of Button 2 , all the data should go to controller again.

I’m not seeing any JavaScript in the code you’ve provided - should there be some there?

1 Like

Well the general approach would be to send the form data to the server using AJAX, and depending on the response, show the rest of the form or not. Can’t help you with JSP though, I’m afraid.

@m3g4p0p @chrisofarabia

I am new to ajax. Can you give me a hint as to how to submit a form from first button and then based on conditions, show the remaining form and then submit again.

This is what I am trying to do as of now:

JSP Modification:

<button type="button" id="ButtonOne" class="btn btn-primary-dark before-panel-margin">Button 1</button>

JS:

$("#ButtonOne").on("click", function() {
		var mobileNumber=$('mobileNumber').val();
		alert("Yo!");
		$.ajax({
			type:'POST',
			url:'/insurance/validate',
			});
	});

I am getting the alert msg but get a error in console:

POST https://localhost:9002/insurance/validate 405 (Method Not Allowed)

Controller where I want both forms to come:

 @RequestMapping(value = "/submit", method = RequestMethod.POST)
	public String submitInsurancePage(final InsuranceForm insuranceForm, final Model model) throws CMSItemNotFoundException
	{
		String mobileNumber = null;

Did you have a look at the two MDN articles I linked? Anyway, as you’re now using jQuery you can also use its .serialize() method. Again, I don’t know about JSP, but this is how a very basic (client side) example might look like:

CSS

.hidden {
  display: none;
}

HTML

<form>
  <input type="text" name="firstName" />
  <input type="text" name="lastName" />
  <input type="button" value="check" id="validate" />
  
  <div class="hidden">
    <input type="text" name="additionalValue" />
    <input type="submit" value="submit" />
  </div>
</form>

JS

// Note that we're not listening to the submit
// event at this point; the real submit button
// is shown later, depending on the response
$('#validate').click(function() {

  // Serialize the form data; usually it will
  // be available to the back end as a key/value
  // pair for each input
  var formData = $('form').serialize();
  
  // Send the form data to the server using
  // AJAX; on success, call the responseHandler
  // function
  $.ajax({
    type: 'POST',
    url: 'https://localhost:9002/insurance/validate',
    data: formData,
    success: responseHandler
  });
});

// This function gets called when the AJAX request
// was successful, and gets the response passed as
// a an argument
var responseHandler = function(response) {

  // Here it depends on what kind of response the server
  // sends; assuming it's simply either "true" or not: 
  if (response == true) {
    $('form .hidden').show();
  } else {
    alert('Form validation failed!');
  }
};

If the response is true here, the hidden part of the form will be shown, including the actual submit button (which won’t require any further client side logic then).

As the message says, it means that your local setup doesn’t allow the POST method. Note that you’re not sending any data anyway, though. If you’re having trouble with the JSP part, you might ask in a dedicated thread so that JSP experts might chime in.

@m3g4p0p @chrisofarabia

Thanks a lot. I have made some progress.

Another UI doubt for same form.

mandatory="true"

Since now with jQuery, the button type= "button", the mandatory fields are not validated. Obviously, I cannot change it to type=submit. So how can I make sure that mandatory="true" does it work with the button click as well

makes no sense with buttons - either the button has been pressed to do whatever the button does or it hasn’t been pressed.Once it has been pressed, if it doesn’t actually submit the form then it would return to its unclicked state - so the test for mandatory can never be true.

Any suggesstion on how can we achieve it. Need it as per my requirement.

Use something other than a button - something that can be made mandatory.

When the button gets clicked, you could change the value of an additional type="hidden" input element accordingly… but as @felgall says, this doesn’t really make sense. Maybe it’s a checkbox you want?

@m3g4p0p

Hi,

I have taken your suggestion to go with ajax. Thanks a lot for that.
But now the problem is that when the user press enter key instead of clicking on button, it internally takes the second button that is of type submit.

How can I make the enter key to click the button one(Validate) initially. When complete form is displayed, enter key should submit the form(button 2)

<form>
  <input type="text" name="firstName" />
  <input type="text" name="lastName" />
  <input type="button" value="check" id="validate" />
  
  <div class="hidden">
    <input type="text" name="additionalValue" />
    <input type="submit" value="submit" />
  </div>
</form>

You can override the onsubmit event, and check if the validation has occurred or not. and validate or submit depending on whether the validation is complete.

You’ll want to give the form a unique id, so that scripting can easily attach an event on to the submit event. Don’t attach the event to the submit button, because that will only catch when the user clicks the submit button. You want to override when the form is submitted (which can be done by pressing enter from any form field) instead which is achieved by attaching on the form itself, which also handily includes the submit button too.

<form id="insuranceForm">
...
</form>
function submitHandler(evt) {
    var form = this;
    var isValid = checkIfFormIsValid(form);
    if (isValid === false) {
        evt.preventDefault();
        document.querySelector("#validate").click();
    } else {
        form.submit();
    }
}
document.querySelector("#insuranceForm").addEventSelector("submit", submitHandler, false);

You just now need to figure out the checkIfFormIsValid function.

Hi Paul,

Thanks for the guidance.
Where should document.querySelector("#insuranceForm").addEventSelector("submit", submitHandler, false);

be placed? In jsp or the js?

Am new to UI, sorry if it is a silly question because am not able to do what you told.

@Paul_Wilkins @m3g4p0p

Also, I am getting an error in console as document.querySelector(…).addEventSelector is not a function

Yes, that happens hen querySelector cannot find an element that matches the selector.

Allow me to repeat what I said in the previous post:

Which was followed up by the following example code:

<form id="insuranceForm">
...
</form>

You will need an identifier like that, for the querySelector to find the “#insuranceForm” element.

I have given a unique form id “insuranceFormId” . It shows up in console also. But where should I place document.querySelector(“#insuranceFormId”).addEventSelector(“submit”, submitHandler, false);

In the jsp or the javascript?

@Paul_Wilkins @m3g4p0p

addEventSelector(“submit”, submitHandler, false); is throwing the error. I changed it to
addEventSelector(“submit”, submitHandler(), false). It worked.

But now it is throwing error as Cannot read property ‘preventDefault’ of undefined

that’s usually wrong - unless submitHandler returns the function you want to run when the event is triggered.