Skip to Content Skip to Menu

Form element attribute not changing via javascript

"It just doesn't make sense!"

I definitely said this many times until I managed to figure out why I couldn't change a form attribute via jQuery or even raw javascript. In order to illustrate this I'll give an example.

Example:

Aim was to change the form action via javascript because I wanted it to go to another page if the user had javascript turned on.

HTML:

<form action="process_page.php" id="process_form" method="post">
<!-- form inputs here -->
<input name="action" type="hidden" value="add" /> <!-- main problem -->
</form>

jQuery:

$(document).ready(function(){
$("form#process_form").attr("action","process_page_2.php");
});

The jQuery code is the proper syntax to achieve this. But the DOM has been setup wrong. Notice there was an input with the name "action" which actually overrides the form attribute "action".

Typical Fix:

Rename your input field name attribute. If it still isn't working also check the id attribute name too.