0

I am trying to add form fields to a form before submitting it using JQuery. I've already tried the following stackoverflow questions and they have not worked:

How to add additional fields to form before submit?

jQuery - add additional parameters on submit (NOT ajax)

If I don't add any parameters to the form, the submit works:

$('.submit_button').click(function(){
    $('#quote_form').submit();
});

The code above works. Once I try to add a field, however, the form does not get submitted. It is not reaching the server. Here is the code I am using:

$('.submit_button').click(function(){
    console.log('1');
    $("#quote_form").submit( function(eventObj) {
      console.log('2');
      $(this).append('<input type="hidden" name="dog" value="rover" /> ');   
      return true;
    });
});  

The first console.log appears in the console but the second does not. How do I get this code to work?

Community
  • 1
  • 1
Philip7899
  • 4,599
  • 4
  • 55
  • 114

2 Answers2

1

You're not submitting the form. Try this:

$("#quote_form").submit( function(eventObj) {
   $(this).append('<input type="hidden" name="dog" value="rover" /> ');   
   return true;
});

$('.submit_button').click(function(){
    $("#quote_form").submit();
});

$(..).submit(handler) does not submit but only register a handler function for the submit event. You need to call $(..).submit() without parameters for it to submit.

Alfonso Presa
  • 1,024
  • 7
  • 11
  • Thanks. This works except the information that I need to put into the input is "this" IE "submit_button" because there are two buttons that can be clicked. – Philip7899 Aug 26 '15 at 16:09
0

the second console.log() not appears because you don't stop submitting.

$('.submit_button').click(function(){
    console.log('1');
    $("#quote_form").submit( function(event) {
        event.preventDefault();
        console.log('2');
        $(this).append('<input type="hidden" name="dog" value="rover" /> ');     
        $("#quote_form").submit();
    });
});

I hope this will help you!