0

Note: There are many questions around this topic and I tried some of the solutions and this is how far I got, but now I'm stuck.

I want to have a 'calculate' button which is connected to a servlet and handles user input and a 'generate PDF button' that opens a new tab with a pdf generated from user input. For page flow, I need to put this in a single form.

So I have now:

<form action="/myProject/input" method="post" name="inputForm" onsubmit="return validateForm()" id="inputForm">
    <div>some input fields ...</div>
    <div>
        Results here
        <button type="submit" id="pdf_button" class="button" name="pdf_button">${buttonPrint}</button>
    </div>
    <div>
        some more input fields
        <button type="submit" id="calculate_button" class="button" name="calculate_button">${buttonCalculate}</button>
    </div>
</form>

Note: Button Value ${X} is language specific, so not suitable for this.

I tried following as suggested here in $(document).ready():

$("#inputForm").on("submit", function() {
  var $btn = $(document.activeElement);

  if (
    $btn.length &&
    $("#inputForm").has($btn) &&
    $btn.is('button[type="submit"]') &&
    $btn.is("[name]")
  ) {
    if ($btn.attr("name") == "pdf_button") {
      console.log("--- IT WORKS UNTIL HERE! ---");

      $("#inputForm").action =
        getContextPath() + "/print?language=" + $("#language").val();
      $("#inputForm").target = "_blank";
    }
  }
});

Since I get the console.log I retrieve the right button. But on print-button click, the calculate-action is executed, not the action from JS. What am I doing wrong?


Until now I had two forms which worked fine, but I want to restructure the page. The previous second form looked like this and was placed right after the first one:

<form action="/myProject/print?language=${lang}"
    method="post" name="printForm" onsubmit="return validateForm()" 
    target="_blank">

    <button type="submit" id="calculate_button" class="button"
        name="calculate_button">${buttonCalculate}</button>
</form>
Vaibhav Bhavsar
  • 432
  • 4
  • 12
Merha
  • 119
  • 13
  • use data attribute instead https://api.jquery.com/data/ – Parth Shah Jul 17 '18 at 09:29
  • @ParthShah $("#inputForm").data("action", "/myPath")? or where/how should I use it? – Merha Jul 17 '18 at 09:35
  • Depending on your server-side tech, you can receive the name of the submit button: *When you click a submit button, the name of that submit button is passed in the request parameters*. More info (C# MVC specific, but the POST still applies) : https://stackoverflow.com/questions/30970159/net-mvc4-actionnameselectorattribute-multiple-buttons-within-view-is-not-workin/33169654#33169654 – freedomn-m Jul 17 '18 at 09:35
  • @freedomn-m so I should redirect in my Java Servlet instead of trying to use JS? – Merha Jul 17 '18 at 09:38

0 Answers0