Reputation: 4425
Here is my example:
var form= $(".anyclass form");
var sf = form.serialize();
$.post(form[0].action,
Let's suppose that there is only one form in the page that fits the criteria.
Why I need to access the action property using [0]
?
Why the .serialize()
is done without [0]
?
Sorry about this newbie question.
Upvotes: 1
Views: 113
Reputation: 339796
Your form
variable returned from $(...)
is a jQuery object that potentially includes references to many form elements.
To access the underlying native DOM elements within that object you either need to use array notation (as above) or form.get(0)
.
As for the differences in usage, .serialize()
is a method of the jQuery object, so has to be called on form
.
However .action
is a DOM attribute, so you need to use the native DOM element to access it, although you could alternatively have used:
form.attr('action')
Upvotes: 2
Reputation: 8814
That's because .serialize() is a jQuery method that applies for all matched elements.
I haven't looked at the source, but I bet there's something like this:
return this.each(function(i, val){
// do stuff
})
And when you do form[0].action
, you're actually returning the first element (the native DOM element) in the set of matched elements, and then accessing it's native property
Upvotes: 1
Reputation: 9929
I think you want to do it like:
$.post(form.attr('action'));
By the way: you are getting all forms within an element with the class .anyclass. This will return multiple forms (if present). Ýou'll be better of if you gave the form some id and get it that way: $('#myForm').
Upvotes: 3
Reputation: 17666
the [0] just gives you the straight DOM Object for the Form,
form === jquery object
form[0] === DOM object
Upvotes: 1