Add jquery.fn.serializeObject
authorOri Livneh <ori@wikimedia.org>
Tue, 2 Dec 2014 19:44:38 +0000 (11:44 -0800)
committerOri Livneh <ori@wikimedia.org>
Tue, 2 Dec 2014 20:38:08 +0000 (12:38 -0800)
Teeny-tiny jQuery plugin to get form data as an object mapping each form
control's name to its value. I needed this for something and I saw this
pattern already in use in mediawiki.searchSuggest.js, so that's two use-cases.
I thought about calling this 'jquery.formData', but since it's a close analog of
jquery.serializeArray, I think this name is appropriate.

Change-Id: I00b6a7fb75a4d5132e7d6715c8867091a161dbb6

resources/Resources.php
resources/src/jquery/jquery.getAttrs.js
resources/src/mediawiki/mediawiki.searchSuggest.js

index f2c3227..9755d25 100644 (file)
@@ -951,6 +951,7 @@ return array(
                        'jquery.client',
                        'jquery.placeholder',
                        'jquery.suggestions',
+                       'jquery.getAttrs',
                        'mediawiki.api',
                ),
        ),
index 5d6a1d4..a2e2be5 100644 (file)
@@ -2,6 +2,16 @@
  * @class jQuery.plugin.getAttrs
  */
 
+function serializeControls( controls ) {
+       var i, data = {}, len = controls.length;
+
+       for ( i = 0; i < len; i++ ) {
+               data[ controls[i].name ] = controls[i].value;
+       }
+
+       return data;
+}
+
 /**
  * Get the attributes of an element directy as a plain object.
  *
  * @return {Object}
  */
 jQuery.fn.getAttrs = function () {
-       var i,
-               map = this[0].attributes,
-               attrs = {},
-               len = map.length;
-
-       for ( i = 0; i < len; i++ ) {
-               attrs[ map[i].name ] = map[i].value;
-       }
+       return serializeControls( this[0].attributes );
+};
 
-       return attrs;
+/**
+ * Get form data as a plain object mapping form control names to their values.
+ *
+ * @return {Object}
+ */
+jQuery.fn.serializeObject = function () {
+       return serializeControls( this.serializeArray() );
 };
 
 /**
index a214cb3..d372e8f 100644 (file)
                        baseHref = $form.attr( 'action' );
                        baseHref += baseHref.indexOf( '?' ) > -1 ? '&' : '?';
 
-                       linkParams = {};
-                       $.each( $form.serializeArray(), function ( idx, obj ) {
-                               linkParams[ obj.name ] = obj.value;
-                       } );
+                       linkParams = $form.serializeObject();
 
                        return {
                                textParam: context.data.$textbox.attr( 'name' ),