Alex
Alex

Reputation: 68416

jQuery - get array with input names as keys

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();

Upvotes: 2

Views: 3435

Answers (3)

user113716
user113716

Reputation: 322472

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.

var result = {};

$.each(this.form.elements, function() {
    result[ this.name ] = this;
});

Regarding your update, this line:

var matches1 = that.toArray();  

...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.

var matches1 = $.toArray( that );  

...although I don't know why you'd want to turn the jQuery object representing all <input> element into an Array on each change event.

This line:

var matches2 = this.form.elements;  // this works.

... 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 of makeArray(). The toArray() method is a wrapper for .get() and does exactly the same thing.

Upvotes: 3

Anurag
Anurag

Reputation: 141869

form.elements returns an object of HTMLCollection or HTMLFormControlsCollection in HTML5.

The elements in these objects are accessible by index or name. So if you have a form with a single input element named "login", you could do:

form.elements.[0]

or

form.elements["login"]

to access the same element. You could simulate such an object by adding two entries for each form element with its corresponding index and name. But if form.elements works for you, I'd recommend using that directly.

Upvotes: 1

000
000

Reputation: 280

Serialize is a possible choice. http://api.jquery.com/serializeArray/

$(this).serializeArray() rertuns it. :)

Upvotes: 2

Related Questions