48

Hi I am trying to get "a" tag as a submit button. I found a code somewhere in the web. But it didn't work.

<a href="#" onclick="this.form.submit()">Submit</a>

Is there any code for to achieve my need?

theepan
  • 483
  • 1
  • 4
  • 4

7 Answers7

46

Give the form an id, and then:

document.getElementById("yourFormId").submit();

Best practice would probably be to give your link an id too, and get rid of the event handler:

document.getElementById("yourLinkId").onclick = function() {
    document.getElementById("yourFormId").submit();
}
James Allardice
  • 164,175
  • 21
  • 332
  • 312
40

Try this code:

<form id="myform">
  <!-- form elements -->
  <a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>

But users with disabled JavaScript won't be able to submit the form, so you could add the following code:

<noscript>
  <input type="submit" value="Submit form!" />
</noscript>
ComFreek
  • 29,044
  • 18
  • 104
  • 156
18

Supposing the form is the direct parent you can do:

<a href='#' onclick='this.parentNode.submit(); return false;'>submit</a>

If not you can access through the forms name attribute like this:

<a href='#' onclick='document.forms["myform"].submit(); return false;'>submit</a>

See both examples here: http://jsfiddle.net/WEZDC/1/

amosrivera
  • 26,114
  • 9
  • 67
  • 76
  • 1
    Or use [`closest()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest) to get the closest form: `` – adriaan Jul 02 '20 at 10:15
7

This is an improve of @ComFreek ans:

<form id="myform">
  <!-- form elements -->
  <a href="javascript:;" onclick="document.getElementById('myform').submit()">Submit</a>
</form>

So the will not trigger action and reload your page. Specially if your are developing with a framework with SPA.

1

Try something like below

 <a href="#" onclick="this.forms['formName'].submit()">Submit</a> 
SoundwaveUwU
  • 138
  • 1
  • 2
  • 12
Praveen
  • 1,449
  • 16
  • 25
0

document.getElementById('myForm').action="javascript:function("+a+","+b+")";

You can change the action attribute, and put some variables as params of a function.

DyC
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 14 '22 at 02:36
-6

in my opinion the easiest way would be somthing like this:

<?php>
echo '<a href="link.php?submit='.$value.'">Submit</a>';
</?>

within the "link.php" you can request the value like this:

$_REQUEST['submit']