JQuery descriptor deserialization for all inputs

I used each function simple to deserialize the form:

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

but I cannot get it to work for elements of a non-standard form (i.e. radio buttons / checkboxes). I play with different examples several times and cannot make it work. Does anyone know an elegant solution for this?

+4
source share
2 answers

try the following:

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"); } } } }) 
+3
source

Perhaps a plugin like this can help.

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

It seems that it has not been updated in a couple of years.

+1
source

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


All Articles