1

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

$('#submit').click(function(e){
    e.preventDefault();
    console.log(e.form) // I got undefined?
});
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Eunice Chia
  • 355
  • 1
  • 11

4 Answers4

2

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:

$('#submit').click(function(e){
    e.preventDefault();
    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
Jai
  • 74,255
  • 12
  • 74
  • 103
0

With your expression you try to select an existing DOM element with id="submit". You can have a look at this post, which I think answers your question, it shows you how to create a button dynamically with jQuery:

How to add a button dynamically using jquery

Community
  • 1
  • 1
Csaba Benko
  • 1,101
  • 8
  • 15
0

Also noteworthy as posted here:

jquery/js -- How do I select the parent form based on which submit button is clicked?

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});
Community
  • 1
  • 1
stewo
  • 443
  • 4
  • 11
0

To get the form based on elements inside it you could use just element.form :

$('#submit').click(function(e){
    e.preventDefault();

    console.log(this.form);
});

e : represent the event that why we use e.preventDefault(); so it will prevent the default event.

this : represent current clicked element submit that why we could use this.form to get the parent form.

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101