6

I have the following form:

<form id="editForm">
<input class="span12" name="name" type="text" placeholder="Product name...">
<input class="span12" name="sku" type="text" placeholder="SKU...">
<input name="basePrice" class="span12" type="text" placeholder="Base price...">
</form>

How do I turn that into an associative array that can be accessed like the following?

formArray['name'], formArray['sku'], etc.

3
  • in other words, you want an object with key/value pairs. You'll have to do it manually by iterating over the form inputs or accessing them 1 by 1. Commented Nov 6, 2013 at 19:14
  • 1
    @imperium2335 Right, that's why i didn't suggest serializeArray. Commented Nov 6, 2013 at 19:42
  • Have you check this : stackoverflow.com/questions/1184624/… Commented Mar 26, 2018 at 8:01

1 Answer 1

15

Here's a dead-simple way:

$.fn.form = function() {
    var formData = {};
    this.find('[name]').each(function() {
        formData[this.name] = this.value;  
    })
    return formData;
};

// use like
var data = $('#editForm').form();

This is totally unsafe and just grabs everything with a name, but it should get you started.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a terrific answer. Just check the values server-side and you are good.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.