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);

});
\$\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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.