Eunice Chia Eunice Chia - 2 months ago 7x
jQuery Question

Javascript this form equivalent to jquery form

I have this in native JS

<button id="submit" onclick="javascript:validateForm(this.form);return false;">Submit</button>

how do I do it in jquery? I tried

console.log(e.form) // I got undefined?

Jai Jai

In your code e is the event bound on the #submit button and it is an object called event object. It has several properties but not the form. So,

You can use this:

    var form = $(this).closest('form'); // <----gets you the form
    console.log(form) // I got undefined?

Can be understood that #submit button is inside the form so, you have to traverse up in the DOM tree with .closest() to get the form.

if you require to have a native DOM node from jquery code, you can append [0] here:

var form = $(this).closest('form')[0]; // <----gets you the native DOM node of form