Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn a form into an associative array in Jquery [duplicate]

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.

like image 488
imperium2335 Avatar asked Nov 06 '13 19:11

imperium2335


1 Answers

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.

like image 173
Mathletics Avatar answered Oct 19 '22 17:10

Mathletics