简体   繁体   中英

Adding fields to form with JQuery submit()

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?

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM