⬆️ ⬇️

Javascript - getting data from a form into a hash array

A simple function that may be useful to someone.



Purpose: to send data from the form using the jQuery.post () method without reloading the page.

Task: get the data from the form in the form of a hash array.



  function getFormHash (formSelector)
 {      
       hash = {};
       inputs = {};
       jQuery (formSelector + 'input'). each (function () {
             name = jQuery (this) .attr ('name');
             value = jQuery (this) .attr ('value');
             type = jQuery (this) .attr ('type');
             if (name.substr (name.length-2, 2) == '[]]) {
                   name = name.substr (0, name.length-2)
                   if (typeof (inputs [name]) == 'undefined') {
                         inputs [name] = 0;
                   }
                   else {
                         inputs [name] ++;
                   }
                   if (type.toUpperCase ()! = 'CHECKBOX' || jQuery (this) .attr ('checked') == true) {
                         hash [name + '[' + inputs [name] + ']'] = value;
                   }
             }
             else {
                   hash [name] = value;
             }
       });

       jQuery (formSelector + 'select'). each (function () {n
             name = jQuery (this) .attr ('name');
             multiple = jQuery (this) .attr ('multiple');
             if (typeof (name)! == 'undefined') {
                   i = 0;
                   jQuery (this) .children ('option'). each (function () {
                         if (jQuery (this) .attr ('selected')) {
                               value = jQuery (this) .attr ('value');
                               if (multiple == true)
                                     hash [name + '[' + i + ']'] = value;
                               else
                                     hash [name] = value;
                               i ++;
                         }
                   });
             }
       });

       jQuery (formSelector + 'textarea'). each (function () {
             name = jQuery (this) .attr ('name');
             value = jQuery (this) .html ();
             hash [name] = value;
       });
      
       return hash;
 } 


')

The function simply passes through all input, select, and textarea in the form, forming a hash array. Names in the form of name [] and multiple for select are taken into account.

If you missed something, tell me.

If you already have a commonly used ready-made solution, also tell me.

Source: https://habr.com/ru/post/43042/



All Articles