I have a form. When I click the save button, I want to create an object from the data and pass that info to HTML elements on the same page (div.form_content).
I decided, instead of creating a variable for each HTML element to create an array of HTML elements. I know the first HTML element is going to contain the first object property, the second html element will contain the second obj property, and so on...
What I have done below seems a little repetitive and not very DRY, and I was wondering if someone could recommend a better way. For example, if my form has to grow to 12 input fields, what I am doing now would be pretty clunky. I tried running a loop to prevent the line-by-line assignments, but couldn't figure it out. (By the way, I needed to create an object from the form data because I will need to stringify it to JSON notation to pass to the server, but I got that part.)
$('#save').click(function() {
var form_Array = $('form').serializeArray();
// Create an Array of HTML elements
var el_Array = $('div.form_content').children();
// create empty object
var obj = {};
// loop through serialized form object and assign new object keys from this.name and their values from this.value
$.each(form_Array, function() {
obj[this.name] = this.value;
});
// populate the html elements with contents of the newly created object
$(el_Array[0]).html(obj.fname);
$(el_Array[1]).html(obj.lname);
$(el_Array[2]).html(obj.phone);
$(el_Array[3]).html(obj.fax);
});