How to Fix: serializeArray() Returning Empty Array in jQuery

In jQuery, the serializeArray() is commonly used by developers to convert inputs from an array into key-value pairs.

However, one common issue is serializeArray() returning an empty array or an array with no values. This is particularly frustrating when you expect to collect input data and store it in an array for further processing.

In this tutorial, I provide you with the solution to this issue, along with an example.

Solution to Fix serializeArray() Returning Empty Array in jQuery

The .serializeArray() only works on form elements with a name attribute. The input fields that do not have name attributes are ignored and not processed.

To resolve this, you need to add a name attribute to each of the input fields.

Let’s say you have a form containing a list of items with prices. You want to serialize these inputs into an array using .serializeArray():

<fieldset id='itemInformation'>
    <h2>Items</h2>
    <div class="itemGroup">
        <input type="text" id="item1Name" value="Item 1" class="itemNames">
        <input type="number" step="0.01" id="item1Price" value="0.00">
    </div>
    <div class="itemGroup">
        <input type="text" id="item2Name" value="Item 2" class="itemNames">
        <input type="number" step="0.01" id="item2Price" value="0.00">
    </div>
    <div class="itemGroup">
        <input type="text" id="item3Name" value="Item 3" class="itemNames">
        <input type="number" step="0.01" id="item3Price" value="0.00">
    </div>
    <div class="buttons">
        <button class="previousButton btn">Previous</button>
        <button class="nextButton btn">Next</button>
    </div>
</fieldset>

You’re using the following JS bind the .nextButton to log the serialized array:

$('#itemInformation .nextButton').bind('click', function (event) {
    event.preventDefault();

    console.log($('.itemGroup').serializeArray());
});

This will return an empty array in the console since none of the fields have a name attribute.

You can solve this issue by adding a name attribute to each input field in the form. For example:

<div class="itemGroup">
    <input type="text" id="item1Name" value="Item 1" class="itemNames" name="itemNames[]">
    <input type="number" step="0.01" id="item1Price" value="0.00" name="itemPrices[]">
</div>

Now, the serializeArray() will be able to identify each field based on name attribute and produce the desired results.

I hope this tutorial has helped you fix serializeArray() returning empty array issue. Thanks for reading!

Siddharth Nandava

Article by

Siddharth Nandava

Siddharth Nandava is an enthusiastic Jr Magento developer at Meetanshi. Apart from the work, you can find him learning new things and spending quality time with his family.