开发者

Jquery get all input values and create an array (with names)

开发者 https://www.devze.com 2022-12-12 14:45 出处:网络
Hay guys, I\'m doing some work where i have a large collection of forms. Seems these aren\'t \'posted\' the traditional way (i.e using a submit button). I need a way to collect all the names and value

Hay guys, I'm doing some work where i have a large collection of forms. Seems these aren't 'posted' the traditional way (i.e using a submit button). I need a way to collect all the names and values of all form data when cl开发者_如何转开发icking a link (document.location is then used for redirects).

I want names to stay intact so that i can used a simple PHP script to work with the data.

any suggestions?


Might I suggest Serialize Form to 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 do:

var formArray = $("#myform").serializeObject();


$.fn.valuesArr = function()
{
    var a = [];
    jQuery.each(this, function(i, field){
        a.push($.trim(field.value));
    });
    return a;
}

USE:

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


You could use something like my submit helper as a base

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

instead of a 'serializeArray()' i would use 'serialize()' and instead of posting it using ajax you could do whatever you want.

Sorry, dont have more time right now, but hopefully this snippet helps you.


cletus's answer is the best one in terms of efficency.

This is however another working solution that does not rely on 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 will be an array of myObject, each of them containing a name property and a value property.

Use your selector instead of $('span').


but all this functions dont work witch array names in inputs.

example -

this is correct for submit post form but when serialize i get

form[type[]]:2

this is not correct - i need - form[type][]:2

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号