开发者

How to find parent form from element?

开发者 https://www.devze.com 2023-01-13 14:06 出处:网络
I am trying to find parent form from element using code below: <form id=\"f1\" action=\"action1.html\">

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/jav开发者_如何学Pythonascript" >
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


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


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()


Button element has form property http://www.w3schools.com/jsref/dom_obj_pushbutton.asp

buttonElement.form


$(".whatever").parents("form");


<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

0

精彩评论

暂无评论...
验证码 换一张
取 消