4

I've been using a simple each function for deserializing a form:

  data = { key : val, ... };
  form = $('#formId');
  $.each(data, function(val,i) {
    form.find('*[name="' + val + '"]').val(data[val]);
  });

but I can't seem to get it to work for non-standard form elements (i.e. radio buttons/checkboxes). I've been playing with different examples for a few hours and can't get it to work. Anyone know an elegant solution for this?

2
  • 1
    Have you looked into datalink plugin (api.jquery.com/link)?
    – amit_g
    Commented Mar 4, 2011 at 17:34
  • looking for a non-plugin solution, but thanks for the suggestion
    – wajiw
    Commented Mar 4, 2011 at 17:36

2 Answers 2

3

try this:

example

html:

<form id="formId">
    a: <input name="a" /><br />
    b: <input name="b" /><br />
    c: <input type="checkbox" name="c" /><br />
    d: <select name="d"><option value="d1">d1</option><option value="d2">d2</option></select><br />
    e: <input type="radio" value="1" name="e" /><br />
    e: <input type="radio" value="2" name="e" /><br />
    e: <input type="radio" value="3" name="e" /><br />
    f: <input type="checkbox" name="f" /><br />
</form>

js:

var 
    data = { a: "value for a", b: "value for b", c: false, d:"d2", e: "2", f:true },
   form = $('#formId');

   $.each(data, function(i, el) {

      var 
          fel = form.find('*[name="' + i + '"]'),
          type = "", tag = "";

       if (fel.length > 0) {

           tag = fel[0].tagName.toLowerCase();

           if (tag == "select" || tag == "textarea") { //...
              $(fel).val(el);
           }
           else if (tag == "input") {
              type = $(fel[0]).attr("type");
               if (type == "text" || type == "password" || type == "hidden") {
                  fel.val(el);
               } 
               else if (type == "checkbox") {
                  if (el)  
                     fel.attr("checked", "checked"); 
               }
               else if (type == "radio") {
                   fel.filter('[value="'+el+'"]').attr("checked", "checked"); 
               }
           }
       }
   })
1
  • this code doesn't loop through multiple elements of the same name but it's close enough. Thanks!
    – wajiw
    Commented Mar 6, 2011 at 18:25
1

Maybe a plug-in like this can help.

$('#form-id').deserialize([{'name':'firstname','value':'John'},{'name':'lastname','value':'Resig'}]);

Looks like it hasn't been updated in a couple of years.

1
  • really looking for a non-plugin solution, but I'll check it out. thanks!
    – wajiw
    Commented Mar 4, 2011 at 17:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.