From a444c7264d6659c56341abb304a2a3e8190915ed Mon Sep 17 00:00:00 2001 From: Ori Livneh Date: Tue, 2 Dec 2014 11:44:38 -0800 Subject: [PATCH] Add jquery.fn.serializeObject 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 | 1 + resources/src/jquery/jquery.getAttrs.js | 28 +++++++++++++------ .../src/mediawiki/mediawiki.searchSuggest.js | 5 +--- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/resources/Resources.php b/resources/Resources.php index f2c3227a16..9755d25a09 100644 --- a/resources/Resources.php +++ b/resources/Resources.php @@ -951,6 +951,7 @@ return array( 'jquery.client', 'jquery.placeholder', 'jquery.suggestions', + 'jquery.getAttrs', 'mediawiki.api', ), ), diff --git a/resources/src/jquery/jquery.getAttrs.js b/resources/src/jquery/jquery.getAttrs.js index 5d6a1d442e..a2e2be5987 100644 --- a/resources/src/jquery/jquery.getAttrs.js +++ b/resources/src/jquery/jquery.getAttrs.js @@ -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. * @@ -11,16 +21,16 @@ * @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() ); }; /** diff --git a/resources/src/mediawiki/mediawiki.searchSuggest.js b/resources/src/mediawiki/mediawiki.searchSuggest.js index a214cb3f29..d372e8f438 100644 --- a/resources/src/mediawiki/mediawiki.searchSuggest.js +++ b/resources/src/mediawiki/mediawiki.searchSuggest.js @@ -41,10 +41,7 @@ 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' ), -- 2.20.1