Quantcast
Channel: Adobe Community : Unanswered Discussions - General and cross-application scripting
Viewing all articles
Browse latest Browse all 84

JSON > JavaScript Array - populating form fields

$
0
0

Hello, all,

 

I'm working on a project where the customer has a form to allow a user to filter a database query by name, location, rank, etc.

 

Said customer wants to allow a user to save form data for repeat use (like, choose an option from a select and have the form populated from what was saved.)

 

Currently, I'm using jQuery.serializeArray() to save the form data into an array, then using JSON.stringify() to store it as a string in the database.

 

But I'm having an issue trying to populate the form from that string.  I'm getting it from the database and using JSON.parse() to create a JavaScript array-like object, and using for(i in data) to populate the form.

 

This works GREAT for things like input type="text" or type="password" or textareas.  But I'm having issues trying to select options in a SELECT tag, and checking radio and checkbox inputs from the array.

 

An example of the data I am getting back and using JSON.parse() on would be:

[{"name":"inputa","value":""},{"name":"inputb","value":""},{"name":"inputc","value":""}, //These are text, password and a single select inputs.
{"name":"inputd","value":"inputd_1"},{"name":"inputd","value":"inputd_3"},               //This is three checkboxes, same name, different IDs - two are checked.
{"name":"inpute","value":"Option A"},{"name":"inpute","value":"Option C"},               //This is a select-multiple - two are selected.
{"name":"inputf","value":"Bravo"},                                                       //This is one value of a three radio input array.
{"name":"txtarea","value":""}]                                                           //This is a textarea.

 

Any suggestion on how to check radio/checkbox and choose SELECT options from this?  I've got some JavaScript code that I'll add, here.  The below code is part of the .done() from the $.ajax() that I'm using to get the JSON string from the database, which returns "data".

 

var datab = JSON.parse(data), frm = document.getElementById('formname'), elems = frm.elements;
for(i in elems){    switch(elems[i].type){        case 'text': case 'tel': case 'email': case 'url':            elems[i].value = datab[i].value; //This works just fine.        break;        case 'select-one':            // Not sure what to do here        break;        case 'select-multiple':            // Not sure what to do here        break;        case 'radio': case 'checkbox':            // Not sure what to do here        break;        }    }

 

V/r,

 

^_^


Viewing all articles
Browse latest Browse all 84

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>