jQuery buscar formulario principal

Resuelto kmunky asked hace 14 años • 5 respuestas

tengo este html

<ul>
    <li><form action="#" name="formName"></li>
    <li><input type="text" name="someName" /></li>
    <li><input type="text" name="someOtherName" /></li>
    <li><input type="submit" name="submitButton" value="send"></li>
    <li></form></li>
</ul>

¿Cómo puedo seleccionar el formulario del que input[name="submitButton"]forma parte? (cuando hago clic en el botón enviar, quiero seleccionar el formulario y agregarle algunos campos)

kmunky avatar Oct 26 '09 01:10 kmunky
Aceptado

Sugeriría usar closest, que selecciona el elemento principal más cercano:

$('input[name="submitButton"]').closest("form");

En lugar de filtrar por nombre, haría esto:

$('input[type=submit]').closest("form");
karim79 avatar Oct 25 '2009 18:10 karim79

Puede utilizar la referencia del formulario que existe en todas las entradas, esto es mucho más rápido que .closest()(5 a 10 veces más rápido en Chrome e IE8). También funciona en IE6 y 7.

var input = $('input[type=submit]');
var form = input.length > 0 ? $(input[0].form) : $();
peterjwest avatar Jul 25 '2011 09:07 peterjwest

Para mí, esto parece el más simple/rápido:

$('form input[type=submit]').click(function() { // attach the listener to your button
   var yourWantedObjectIsHere = $(this.form);   // use the native JS object with `this`
});
userfuser avatar Sep 20 '2013 16:09 userfuser