0

On a button click, my page removes one form and replaces it with another using jQuery. When clicking submit on the second form, it does not execute the associated Javascript like it is supposed to.

Instead, it executes that /post route in Express, despite being overridden by the JavaScript. It's like the page does not know how to associate the form submission with the associate JS function, or something.

Here is what the HTML looks like once the first (working) form has been submitted and jQuery has done its magic:

<div class="text-center">
   <form id="ex2"  method="post">
      <div class="btn-group">
         <div class="row" id="mertola"><input name="selected" type="radio" value="selected" /> Yes Please: </div>
         <div class="row" id="email"><input name="email" type="radio" value="yesemail" /> email: </div><br/>
      </div>
      <div class="text-center" id="gobutton">
           <button type="submit" class="btn btn-warning btn-lg text-center">Choose</button>
      </div><br/><br/>
   </form>
</div>

The JavaScript is unchanged the entire time. Here's the javascript for the second form submission:

$("#ex2").submit(function (e) {
  //todo this code is never being executed
  console.log("WAHOOO!!");
  var formResult = $(this).serialize();
  //client.publish('/foo', {text: 'channel2', form: formResult});
  e.preventDefault();
  return false;
});

Hoe do I get the JavaScript to execut? It's a headscratcher.

Dhiraj
  • 31,130
  • 7
  • 57
  • 77
Dirk
  • 2,634
  • 3
  • 26
  • 34
  • 3
    You need event delegation, like: `$("body").on("submit", "#ex2", function (e) { ...` – lmgonzalves Jul 17 '15 at 18:38
  • 1
    Does the form with id "ex2" exist when you bind the submit callback to it? – yvesmancera Jul 17 '15 at 18:42
  • @yvesmancera - that's a great question. I guess no. I wonder .... if I can make it hidden, and then populate it when needed. You have the answer, I think. – Dirk Jul 17 '15 at 18:47
  • @yvesmancera: Tested that option, and it works. Thanks for putting me on the right track. If you make an answer, I'll accept it. – Dirk Jul 17 '15 at 19:35

1 Answers1

1

You can use body on submit form event. Because sometime dynamically generated form or element could not detect its event directly.

For I. E.

$("body").on('submit','#ex2',function (e) {
      //todo this code is never being executed
      console.log("WAHOOO!!");
      var formResult = $(this).serialize();
      //client.publish('/foo', {text: 'channel2', form: formResult});
      e.preventDefault();
      return false;
});
Bhavin Solanki
  • 4,492
  • 3
  • 19
  • 42