Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change form's action attribute

Okay, I must be missing something here because this should be extremely simple, yet it doesn't work...

I have a form on my page with an empty action attribute (action="#"). When the page is ready, I want to change the action attribute to something else. My code is very simple:

HTML:

<form action="#" method="post" id="register"></form>​

jQuery:

$("#register").attr("action", "http://www.test.com");​

Even in a test fiddle, it doesn't work! View the source of the Result frame and you'll see the value of the action attribute is still #.

Where am I going wrong??

like image 200
daGUY Avatar asked Nov 01 '12 01:11

daGUY


People also ask

What does the form's action attribute specify?

The action attribute specifies where to send the form-data when a form is submitted.

Can we change form action in JavaScript?

I found that changing the form's action caused example.com/index.pl (with no page parameter) to be rendered, even though the expected URL ( example.com/page-name ) was displayed in the address bar. To get around this, I used JavaScript to insert a hidden field to set the page parameter.

How do I get a form action URL?

prop() returns the full action url: To use the action attribute of a form use: $( '#myForm' ). attr( 'action' ); like @JAAulde said.


1 Answers

It does work, you aren't testing it properly. Viewing source will show you what the source looked like when the page was loaded, not after it as modified by jQuery. If you alert() action value after it is fetched with jQuery, you will see the new value:

alert($("#register").attr("action"));

It's also generally a good idea to make sure that the DOM has loaded before you make any changes, for which you can use ready():

$(document).ready(function(){ /* your code */ });

Check out: http://jsfiddle.net/wvYjs/2/

like image 139
doublesharp Avatar answered Sep 23 '22 09:09

doublesharp