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
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.
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.
http://api.jquery.com/closest/ will do it. Used like this
$('#elem').closest('form');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With