Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why '$("#form")[0].reset();' works and '$("#form").reset();' not?

I am using form reset method as below in my web pages

$("#form")[0].reset();

But when I use it like the below

$("#form").reset();

It is giving me error.

Why the first method is working and the later is not?

My page is working perfectly. But I would like the reason behind it. The solution is everywhere. But none of them describing the reason behind it.

Note: I checked here and it shows so much answers. Nothing clearly defines the reason.

like image 349
Arun Avatar asked Jul 04 '16 09:07

Arun


3 Answers

The jQuery selector method can return more than one element, so the behaviour is to return an array for consistency's sake. This array is a wrapper for other jQuery methods that can operate on that selection, but manipulating the classic DOM functions requires working on a specific element.

You can do that like you have, with [0] to pull out the first, or you can iterate over them:

$('#form').each(function() { this.reset() });
like image 166
tadman Avatar answered Oct 21 '22 02:10

tadman


Because the reset() method is a member of the HTML form element:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset

And not a method offered by a jQuery object, which is a collection of 0 or more matching elements for your selector (#form)

like image 27
daf Avatar answered Oct 21 '22 02:10

daf


I think the simple reason is it is for forcefully working a javascript function using Jquery

.reset() is not a Jquery native function. It is a Javascript function and we are forcefully using it inside Jquery

like image 1
Arun Avatar answered Oct 21 '22 01:10

Arun