Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the <form> element from an <input> element

I'm trying to select the <form> element from an <input> element with JQuery. I've tried this:

$(".inputClass").parent("form")

but it doesn't seem to work.

like image 283
Manolo Avatar asked Apr 18 '26 10:04

Manolo


2 Answers

In HTML 4 you can grab the ancestor that is a form element (by using parents (plural)), but HTML 5 allows a form control to be associated with a form that it not its ancestor, so you can't rely on that.

Form controls have a form property that will give you their associated form element.

var form = $(".inputClass").prop("form");

You can turn it into a jQuery object if you like.

var $form = $( form );

Or in one line:

var $form = $( $(".inputClass").prop("form") );
like image 62
Quentin Avatar answered Apr 21 '26 00:04

Quentin


Try $(".inputClass").closest("form") because the form may not be the direct parent of the input element

like image 45
Arun P Johny Avatar answered Apr 21 '26 02:04

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!