3

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 clicking 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?

5 Answers 5

7

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();
Sign up to request clarification or add additional context in comments.

Comments

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

USE:

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

Comments

0

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.

1 Comment

I think the combination of $.param and form.serializeArray() is the key. not seralize :). but I'm not sure.
0

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').

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.