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.

Mouse on the Keys
  • 322
  • 1
  • 5
  • 13
imperium2335
  • 23,402
  • 38
  • 111
  • 190
  • 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. – Kevin B Nov 06 '13 at 19:14
  • 1
    @imperium2335 Right, that's why i didn't suggest serializeArray. – Kevin B Nov 06 '13 at 19:42
  • Have you check this : https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery/39248551#39248551 – Bhavik Hirani Mar 26 '18 at 08:01

1 Answers1

14

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.

Evan Davis
  • 35,493
  • 6
  • 50
  • 57