I need get the same type of array that this.form.elements returns, with input names as array keys.
I tried this.toArray(), but even though it looks the same, it’s missing the name keys (the keys are numbers).
Here’s the full function:
(function( $ ) {
$.fn.blah = function(){
var that = this;
return this.each(function(){
$(this).bind('change', function(){
var matches1 = that.toArray(); // this doesn't work
var matches2 = this.form.elements; // this works.
console.log(matches1); // but both arrays look the same. wtf?
console.log(matches2);
return true;
}).change();
});
};
})(jQuery);
using it as $("input").blah();
In javascript you don’t use an Array for named keys. You’d use an Object instead. I assume the values should be the elements themselves.
Regarding your update, this line:…doesn’t work because you’re calling jQuery’s
toArray()against a jQuery object.If you wanted to use that, you’d call it from the library, and pass it the jQuery object.
…although I don’t know why you’d want to turn the jQuery object representing all
<input>element into an Array on eachchangeevent.This line:
… works because it is simply a reference to the elements in the form from the
<input>element that received the event. It uses native DOM API properties to get a collection (that isn’t technically an Array).Had to edit my answer because I was wrong about the use of
toArray(). I was thinking ofmakeArray(). ThetoArray()method is a wrapper for.get()and does exactly the same thing.