Change form action attribute

Well, Iโ€™m missing something here because it should be extremely simple, but 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 script , this will not work! Look at the source of the result frame and you will see that the value of the action attribute is still # .

Where am I mistaken?

+4
source share
1 answer

It works, you are not testing it properly. The view source will show you what the source code looked like when the page loaded, and not after a change in jQuery. If you alert() value of an action after it is selected using jQuery, you will see a new value:

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

As a general rule, it is recommended that the DOM boots before any changes are made for which you can use ready() :

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

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

+5
source

Source: https://habr.com/ru/post/1443351/


All Articles