Turn a form into an associative array in jQuery

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 this into an associative array that can be accessed as shown below?

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

+4
source share
1 answer

Here's the easiest way:

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

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

It is completely unsafe and just captures everything with a name, but it should start you.

+12
source

All Articles