I have this neat little jQuery plugin that allows you to GEt and Set Form field values by passing in a JavaScript Object.
The passed in Object has a property name that matches the Form Field Name and its value will be set on the HTML Form.
I have a demo of it in use here: http://codepen.io/jasondavis/pen/jsmya?editors=101
The main area where I can see this plugin being useful at all is perhaps by filling in a FOrm from an AJAX response.
In the demo below I pass in a JavaScript Object which sets the Form field values.
To make this useful in a real life app, I see it;s main use being to populate a Form from an AJAX response.
So my question, as basic as it may be is something I am uncertain of...
Let's assume you click a button which triggers an AJAX request and the return value is a JSON response. Can I simply pass in the JSON response into this jQuery plugin to fill the form values or does it need to be converted and processed in some other manner first?
The JavaScript object with form form-field-name: 'form-field-value'
looks like this...
var formFieldValues = {
text:'text',
text2:'text2',
text3:'text3',
radio:1
}
The code from my demo:
/*
* jQuery.formFieldValues: get or set all of the name/value pairs from child input controls
* @argument data {array} If included, will populate all child controls.
* @returns element if data was provided, or array of values if not
*/
$.fn.formFieldValues = function(data) {
var els = this.find(':input').get();
if(arguments.length === 0) {
// return all data
data = {};
$.each(els, function() {
if (this.name && !this.disabled && (this.checked
|| /select|textarea/i.test(this.nodeName)
|| /text|hidden|password/i.test(this.type))) {
if(data[this.name] == undefined){
data[this.name] = [];
}
data[this.name].push($(this).val());
}
});
return data;
} else {
$.each(els, function() {
if (this.name && data[this.name]) {
var names = data[this.name];
var $this = $(this);
if(Object.prototype.toString.call(names) !== '[object Array]'){
names = [names]; //backwards compat to old version of this code
}
if(this.type == 'checkbox' || this.type == 'radio') {
var val = $this.val();
var found = false;
for(var i = 0; i < names.length; i++){
if(names[i] == val){
found = true;
break;
}
}
$this.attr("checked", found);
} else {
$this.val(names[0]);
}
}
});
return this;
}
};
$(document).ready(function($) {
// Object with Form field values. (Form Field Name: 'value')
var formFieldValues = {
text:'text',
text2:'text2',
text3:'text3',
radio:1
}
// Set Form Field Values
$('#my-form').formFieldValues(formFieldValues);
// Get Form Field Values
console.log($('#my-form').formFieldValues());
});