1
\$\begingroup\$

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);
});
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 19, 2012 at 13:31
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

I'd say give your "output" elements a data-* attribute that matches the name of the form value it should contain. For instance:

​<div​​​ class="form_content">
 <div data-key="fname"></div>
 <div data-key="lname"></div>
 <div data-key="phone"></div>
 <div data-key="fax"></div>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Then, you can do something like:

$('#save').click(function() {
 var values = $('form').serializeArray(),
 output = $('#values');
 $.each(values, function() {
 output.children("[data-key='" + this.name + "']").text(this.value);
 });
});

Here's a demo

answered Oct 19, 2012 at 14:25
\$\endgroup\$
1
  • \$\begingroup\$ thanks a lot, that worked great...sorry, don't have enough cred to upvote \$\endgroup\$ Commented Oct 19, 2012 at 23:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.