Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find parent form from element?

Tags:

jquery

I am trying to find parent form from element using code below:

<form id="f1" action="action1.html"> form1 <button id="btn1" onclick="testaction(this); return false;" >test form 1</button> </form>   <script type="text/javascript" > function testaction(element) {     var e = $(element.id);     var form = e.parent('form');      alert(form.id); // undefined!!     alert(form.action); // undefined!!     alert(document.forms[0].action); //http://localhost/action1.html } </script> 

It should be something really simple.... Thanks in advance

like image 794
st78 Avatar asked Aug 30 '10 19:08

st78


People also ask

How do I find the form ID of an element?

getElementById("myForm"). elements so this variable isn't representing the form but the list of elements so when you do form. elements[i]. id you try to get the list of elements from the list of elements already stored in the form variable.

How to parent element in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.


2 Answers

http://api.jquery.com/closest/ will do it. Used like this

$('#elem').closest('form'); 
like image 154
Angelo R. Avatar answered Oct 01 '22 13:10

Angelo R.


The problem you're having is that form is a jQuery object, not a DOM object. If you want it to be the form object, you would do e.parent('form').get(0).

Furthermore, you're treating element incorrectly - jQuery takes id selectors in the form #id but you've passed it id.

Here's a working version:

function testaction(element) {   var e = $(element);//element not element.id   var form = e.parent('form').get(0);//.get(0) added    alert(form.id); // undefined!!   alert(form.action); // undefined!!   alert(document.forms[0].action); //http://localhost/action1.html } 

See this for it in action: http://jsfiddle.net/BTmwq/

EDIT: spelling, clarity

like image 20
Ryley Avatar answered Oct 01 '22 11:10

Ryley