How to find parent form from element?

Viewed 69337

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

6 Answers
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="f1" action="action1.html">
form1 <button id="btn1" onclick="get_attr(this); return false;" >test form 1</button>
</form>

<form id="f2" action="action2.html">
form2 <button type="submit" >test form 2</button>
</form>

<script>

$('button[type="submit"]').click(function(e) {
    var form = $(this).parent("form").get(0);
    alert("ID: " + form.id);
    alert("Action: " + form.action);
    e.preventDefault();
});
function get_attr(element) {
    var form = $(element).parent("form").get(0);
    alert("ID: " + form.id);
    alert("Action: " + form.action);
}

</script>

Demo

Related