jQuery - set array values to the input with the same name

jQuery - set array values to the input with the same name

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why jQuery Can't Directly Populate attachments[] Inputs

You are encountering a fundamental mismatch between how jQuery's .val() method works and how HTML forms serialize data for submission. When you execute $('[name="attachments"]').val(attachArray), jQuery attempts to set the value of every element matching that selector to the entire array object. Because an array is an object, it lacks a single string value that can be assigned to the value attribute of an <input> tag.

In your specific case, the input field is hidden:

<input type="hidden" name="attachments[]">

When you pass a JavaScript array directly to .val(), jQuery often coerces this into an empty string or fails to set the property correctly depending on the version and browser. Even if you manage to see a value in the DOM inspector, the form serialization logic is the real culprit here. Upon submission, $_POST['attachments'] expects an array of strings, but the way you are populating the field often results in a single string representation of the array or an empty string, which Laravel interprets as ["attachments"] => [""].

The core issue is that you cannot simply dump a JS array into one hidden input and expect the server to reconstruct it. You must construct a valid serialized string that matches the expected format before assigning it to the input's value attribute.

The Correct Approach: Serialized Arrays

To get an array from JavaScript into a form field named attachments[], you need to serialize the data into a string first. The standard pattern for this is using JSON.stringify() combined with a specific delimiter, or utilizing jQuery's built-in serialization utilities if you are dealing with multiple inputs.

However, since you have a single hidden input intended to hold multiple values (a trick often used for file uploads in legacy systems), the most robust method is to create a string that represents the array elements separated by commas or semicolons, depending on how your backend parser handles it.

If your Laravel controller expects a standard PHP array, you usually don't want to send a JSON string at all unless you are explicitly decoding it. Instead, the hidden input should contain the values in a format the server can parse back into an array.

Here is how to correctly set the value:

// Assuming attachArray contains file names or IDs as strings
var serializedValue = attachArray.join(','); 
// Or if you need them separated differently:
// var serializedValue = attachArray.map(function(item) { return item; }).join(';');

$('#fileList').html('Selected files: ' + serializedValue);

// Set the value of the hidden input to this string
$('input[name="attachments[]"]').val(serializedValue);

Handling Multiple Inputs Dynamically

If your UI involves dynamically adding new file inputs (e.g., clicking "Browse" adds a new row), you cannot rely on a single static input. In modern implementations, it is better to generate unique names for each file input or use a library that handles dynamic form fields automatically.

If you stick with the single hidden input approach, ensure that the string you assign matches exactly what your server-side code expects when it calls explode(',', $_POST['attachments[]']) or similar logic. If your Laravel controller uses $request->file('attachments[]'), it expects a specific structure often associated with file uploads where multiple inputs share the same name attribute.

A Better Pattern for File Attachments

The pattern shown in your HTML snippet—using a hidden input to aggregate values—is common but fragile. It breaks easily when you need to handle multiple files of different types or sizes. A more maintainable approach is to allow multiple distinct <input type="file"> elements, each with the same name attachments[].

When jQuery detects new inputs being added to the DOM (via AJAX or event listeners), you must update their values individually. You cannot loop over an array and set a single selector once; you must iterate over the inputs themselves.

// Example: When adding a new input dynamically
function addAttachmentInput() {
    // Create the new input element
    var newInput = $('<input type="file" name="attachments[]" />');
    
    // Append to your container
    $('#fileList').append(newInput);
}

// When setting values for existing inputs
attachArray.forEach(function(file, index) {
    $('input[name="attachments[]"]').eq(index).val(file.name);
});

Conclusion on Serialization

The reason you are seeing ["attachments"] => [""] in your controller is that jQuery's .val() with an array object fails to coerce the value into a readable string, resulting in an empty string being assigned. To fix this, serialize the array into a string before assignment, or restructure your form to use multiple inputs if you need to handle dynamic file uploads robustly. Always ensure the format of the data in the value attribute aligns with how your backend parses $_POST.

Our network