tags:

views:

42

answers:

3

There are multiple <input /> and <textarea> in the <form>,but none have their id or name.

Is it possible to take a snap shot of every thing inside the <form> and render it when need?

+1  A: 
var formdata = $("#formid").serialize();
cletus
In order to work properly serialize requires that form fields have a name attribute.
rahul
+3  A: 

I'm not sure why you would have a bunch of inputs lacking names and id's, but you could cycle through and generate a name/id for each, and then serialize them using $.serialize();

// Give all a name (e0, e1, e2...)
$(":input").each(function(i){
  $(this).attr("name", "e"+i);
});

// Serialize the data
var data = $("#formid").serialize(); // ex: e0=zip&e1=foo&e2=bar
Jonathan Sampson
It won't work without id and name.
In order to work properly serialize requires that form fields have a name attribute.
rahul
I've addressed this in my updated solution.
Jonathan Sampson
Somehow I need an id/name free solution,sorry...
You have to have some way to identify each field. What good are they if they aren't differentiated?
Jonathan Sampson
It's hard to identify,the order of elements may be different when it's shown
So the order is random, and the fields are anonymous. I'm sorry, but I simply don't see any good in that at all. Can you tell us what it is you're doing?
Jonathan Sampson
If the order is fixed,how to render it efficiently using the serialized data?
@unknown, I'm not sure what you mean. If you tell us what you are doing we can help you better.
Jonathan Sampson
A: 

Updated This answer works for checkboxes, radio buttons, input and textareas. If you wanted select support, just add an additional test/type and parallel setter.

Store the values:

var values = $.map($("form :input"), function(n, i){ 
    if(n.is(':checkbox, :radio'))
      return [n.is(':checked'), "check"];
    else
      return [n.val() , "val"];
};

Restore the values:

$("form :input").each(function(i, el){
   var val = values[i];
   if(val[1] == "check"){
       if(val[0] == true) $(this).attr('checked', 'checked');
       else $(this).removeAttr('checked');
   } else {
       $(this).val(val[1]);
   }
});

This assumes the same order both times. It is (dare I say) impossible to store values without keys and then restore them in a different order, and still have the values match up to the correct fields. You need name or id to differentiate.. period.

Doug Neiner
+1 Another good contribution, Doug.
Jonathan Sampson
@Jonathan Well yours has more merit to actually function... a keyless orderless list is well, quite frightening :) Hey... are you hiding from me on GTalk? :D
Doug Neiner
For radio and checkbox,what I care is whether it's checked or not.Not its value.
What difference does it make if it's clicked if it has no value, sort-order, or identification!?
Jonathan Sampson
@unknown I updated my answer to give you an idea how to use it for other elements.
Doug Neiner