user3580218
user3580218

Reputation: 121

How to submit a form by clicking a link javascript

currently I'm trying to make it so that when the user clicks a link it submits the corresponding form via javascript. I used document.getElementById("id").submit() as a basis on how to send the form so my code should act similar to it in my understanding.

Here's the code:

function run(clickedLink){
clickedLink.id.submit();       //I did it like this since document.getElementById just gets the form id and since link and form have similar id's I thought it would send
}

<form id = 'formId'>
<a href = '#' id = 'formId' onclick = run(this)>Link</a>
</form>

I tried going with name = 'formId' too but it still doesn't run as I wanted it too.

Note: doing this since this code iterates dynamically and the id gets updated i.e. formID1, formID2...

Better ways to implement this are welcome too

Upvotes: 0

Views: 2972

Answers (4)

Vedant Terkar
Vedant Terkar

Reputation: 4682

One Basic thing:

-ID's are used to Uniquely Describe The Element in DOM Hierarchy. Please Don't Repeat it. (it is really bad)

Now to the answer:

function run(x){
var y=findParentForm(x); /* if Id's aren't Unique */
// If iD's are Unique :- var y=document.getElementById("formId");
y.submit();
}

function findParentForm(elem){ 
/* 
This function will find exact parent form 
even if link or elem is inside <div> or other complex DOM structure
This will Only return the parent <form> of that elemnt 
*/ 
var parent = elem.parentNode; 
if(parent && parent.tagName != 'FORM'){
parent = findParentForm(parent);
}
return parent;
}

<form id='formId' action="Server Side Script" method="GET/POST">
<a href='#' id='formId' onclick ="run(this);">Link</a> <!-- change id of link -->
</form>

Upvotes: 0

Ankur Aggarwal
Ankur Aggarwal

Reputation: 3101

You cannot use same id on the same page for more than one element. This is against HTML and DOM specifications https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really .

You can change it to class if you want to reuse or you can change the id itself of other element. Also links are not recommended to submit the form. Their job is to navigate

Upvotes: 1

Dot_NET Pro
Dot_NET Pro

Reputation: 2123

Try this:

<a href="#" onclick="document.forms[0].v.value='Link1';
document.forms[0].submit();">Link 1</a>

Upvotes: 0

T J
T J

Reputation: 43156

Modify your function as follows

function run(clickedLink){
  clickedLink.parentNode.submit(); // parentNode refers to the form element
}

Upvotes: 1

Related Questions