Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the form action dynamically with jQuery

I have a form on my page that looks like so:

<form action="/home/email" enctype="multipart/form-data" id="email-form" method="post">
// form elements
</form>

Depending on the page, I would like to dynamically change the attributes of the form with jQuery; specifically the action attribute.

$('#send-email').click(function () {
   $('#email-form').attr('action', '@Url.Action("emailaccounting", "home")')
 )};

The jQuery above successfully renders to:

<form action="/home/emailaccounting" enctype="multipart/form-data" id="email-form" method="post">
// form elements
</form>

So I'm able to alter the form attributes when clicking a link that opens a popup form to send an email. However, when I submit the form, the action that gets hit is the original - "email" not "emailaccounting".

I played around a bit more and on the submit click handler for the email form, I added the following:

  $('.send-email').click(function (e) {
    // The original form action post will be hit without this...
    e.preventDefault();
    $('#email-form').submit();
  };

With the above snippet, the correct action -- "emailaccounting" is called. Why? I don't know...I'm hoping someone can explain that. But I'm not out of the woods yet - I have an input element to upload a file. Now when I try to upload a file on the same form that worked previously, I hit submit and it goes to the "email" action. If I do not attempt to do a file upload, it hits the "emailaccounting" action.

  1. Why does the e.preventDefault() followed by the submit of the form hit the correct action?
  2. Why does uploading a file direct it to the original form action; not the one altered by jQuery?

Thanks!

like image 782
Mike Avatar asked Oct 06 '11 20:10

Mike


1 Answers

I tried like below and it worked for me

$('#send-email').click(function () {
   $('#email-form').attr('action', '/home/emailaccounting')
 )};
like image 101
Murthy M Avatar answered Oct 27 '22 18:10

Murthy M