mamal 22

I'm looking for the right jquery selector to find the <form> element that contains a particular element located by class. Not quite sure how to do this. What I mean is, I want to be able to select the containing form for an element, sort of like what:

$(".submitbutton1:parent form") 

might do for the following HTML. That's not a real locator obviously, but hopefully it's legible to see what I'm going for.

<form>
    <input type='text'></input>
    <input type='button' class='submitbutton1'>
</form>
<form>
    <input type='text'></input>
    <input type='button' class='submitbutton2'>
</form>

How would I get the containing form with ".submitbutton1" as a starting point?

Cheers

3 answers

mamal 22
4
points
This was chosen as the best answer

hmm, I see that :

$('form:has(.submitbutton1)')

actually works well.

Answered almost 8 years ago by mamal
  • +1 for answering your own question. Abinadi Ayerdis almost 8 years ago
Mottie 1134
1
point

There is a good way to get to the form from your selector button using .closest() (link)

$('.submitbutton1').closest('form')
Answered almost 8 years ago by Mottie
o.k.w 2355
0
points

mamal's answer is perfect for your requirement (+1 for that answer). I am just curious to know why do you need such an implementation where the form is distinguished by an child elemen's css class?

Isn't the following more specific and semantically more correct? I might be wrong, but can't help asking. :)

<form>
    <input type='text'></input>
    <input type='button' id='submitbutton1' class='buttonClass1'>
</form>
<form>
    <input type='text'></input>
    <input type='button' id='submitbutton2' class='buttonClass2'>
</form>

jQuery Selector:

$('form:has(#submitbutton1)')
Answered almost 8 years ago by o.k.w