tags:

views:

47

answers:

4

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>

Whole sample is available at http://dl.dropbox.com/u/5079317/HTMLPage1.htm

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

+1  A: 

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

$('#elem').closest('form');
Angelo R.
A: 
$(".whatever").parents("form");
Sruly
+1  A: 

Throw the inline event handler aboard and stay unobtrusive here.

$(document).ready(function(){
   $('#btn1').bind('click', function(){
      var form = $(this).closest('form')[0];

      alert(form.id); // defined
      alert(form.action); // defined
   });
});

Ref.: .closest(), .bind()

jAndy
+1  A: 

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

Ryley