HTML5 / JavaScript / JQuery - Best way to get form associated with input

110
January 10, 2020, at 12:00 PM

Before HTML5, I used to be able to easily find the form associated with an input using jQuery, because all inputs were contained within the form element.

For example, with jQuery I would do something like:

jQuery('.info-container input').closest('form')

I still would like to use jQuery because I use some features that are easier to implement in jQuery. But, with HTML5, inputs can be outside of the form element. For example the following can be anywhere in the HTML but still part of the form:

<input name='city' form='address_form'>

Is there any easy way in jQuery to get the form associated with a given input/button/select ?

Answer 1

You can get the form property to get the associated form.

$($('input[name=city]').prop('form'))

I believe this will work whether the input is inside a form or uses the form attribute to connect with a form.

Answer 2

How about just get list using this.

var inputs = $(document).find('input[form="address_form"]');

then you can find what input you want within form "address_form" using their name. But if you just need one element, just like this

var inputs = $(document).find('input[form="address_form"][name="city"]');
READ ALSO
getting error when I use destructuring assignment to simplify my props

getting error when I use destructuring assignment to simplify my props

I'm working on destructuring on all props in this componentWhen I store all my props using a variable assignment the code works, but when I store my props in the function parameters I get an error message

111
Angular 8 - Rearrange dynamically created components via drag and drop

Angular 8 - Rearrange dynamically created components via drag and drop

I am currently creating a dynamic questionnaire builder where the user can choose from a list of input fields(eg textbox, checkbox)

111
How to get two queries from firestore?

How to get two queries from firestore?

I use redux and want to know how to take and process two queries from firesotre

141
Initialize using patchValue for template driven forms

Initialize using patchValue for template driven forms

I use template driven and am trying to initialize my form using patchValue and it is not working

140