Drupal website specialists.

Submit a form with an anchor tag using JavaScript and supply an action

Posted 21/July/2010 by neubreed

I needed to submit a form via a standard link. I initially used simple method like this:

<form name="myform">
<input type=text name="domainname">
<a href="javascript:document.myform.submit();">Submit</a>
</form>

This works fine, but I also had a few other submit buttons on the same page that performed different actions. So I created a function and included it in the to update a hidden field with the value of my action like so:

function submitForm(id, action){
	var myform = document.getElementById(id);
	myform.innerHTML += "<input type='hidden' name='"+ action +"' value='" + action +"'>";
	myform.submit();
    return false;
}

For some reason that didn't work in Firefox so I revised the code to the following snippet, which creates an input object instead of appending the HTML:

function submitForm(id, action){
	var myform = document.getElementById(id);
 
    if (document.createElement) {
        input = document.createElement('input');
        input.type = 'hidden';
        input.name = action;
        input.value = action;
        myform.appendChild(input);
    }
	myform.submit();
    return false;
}

This code doesn't have much validation to it but I have successfully executed this in IE 6 to 8, Firefox, Opera and Chrome.