How can I set the form action through JavaScript?
You cannot invoke JavaScript functions in standard HTML attributes other than onXXX
. Just assign it during window onload.
<script type="text/javascript">
window.onload = function() {
document.myform.action = get_action();
}
function get_action() {
return form_action;
}
</script>
<form name="myform">
...
</form>
You see that I've given the form a name
, so that it's easily accessible in document
.
Alternatively, you can also do it during submit
event:
<script type="text/javascript">
function get_action(form) {
form.action = form_action;
}
</script>
<form onsubmit="get_action(this);">
...
</form>
Very easy solution with jQuery:
$('#myFormId').attr('action', 'myNewActionTarget.html');
Your form:
<form action=get_action() id="myFormId">
...
</form>
Plain JavaScript:
document.getElementById('form_id').action; //Will retrieve it
document.getElementById('form_id').action = "script.php"; //Will set it
Using jQuery...
$("#form_id").attr("action"); //Will retrieve it
$("#form_id").attr("action", "/script.php"); //Will set it