JQuery gets all input values ​​and creates an array (with names)

Sen guys, I do some work where I have a large collection of forms. It seems that they are not “sent” in the traditional way (for example, using the submit button). I need a way to collect all the names and values ​​of all form data when a link is clicked (document.location is then used to redirect).

I want the names to remain intact so that I can use a simple PHP script to work with the data.

any suggestions?

+3
source share
5 answers

May I suggest Serializing the form for JSON :

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

and then you can:

var formArray = $("#myform").serializeObject();
+7
$.fn.valuesArr = function()
{
    var a = [];
    jQuery.each(this, function(i, field){
        a.push($.trim(field.value));
    });
    return a;
}

:

var myArr = $('input', $parentJQelem).valuesArr();
+1

-

function submit(form) {
  var form = $(form);
  $.ajax(
    { data: $.param( form.serializeArray()),
      dataType:'script',
      type:'post',
      url: form.attr("action")});
}

"serializeArray()" "serialize()", ajax , .

, , , , .

0

cletus .

, JSON:

//this is my object I will fill my array with
function myObject(name, value)
{
    this.name = name;
    this.value = value;
}

var arr = $.map(
    $('span'), function (item) {
       var $item = $(item); //no need to $(item) 2 times
       return new 
         myObject(
           $item.attr("name"),     //name field
           $item.text()            //value field
         );
    }
);

arr myObject, name value.

$('span').

0

.

example -

,

[ []]: 2

- [type] []: 2

0
source

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


All Articles