Skip to content
Advertisement

Create PHP friendly array for checkboxes with jQuery

The title of the question might not be very explaining and I would really appreciate anyone who can help me with a solution. It’s a special case where I have no access to the PHP file and can’t change anything there and I need another solution which I really couldn’t find anywhere.

Here is my question: I have a form with a hidden value:

<form id="myForm" action="" method="POST">
   <input type="hidden" name="colors[]" value="">
   <input type="submit">
</form>

I also have created an array create with javascript with some values:

<script>
  var myArray = new Array();
  myArray.push('red');
  myArray.push('yellow');
  myArray.push('green');
</script>

I then have a random button somewhere no the page(doesn’t really matter where)

<button id="myButton">Add to hidden array</button>

So the thing I wanna do is, that when I click the button id="myButton", I want a jQuery solution to add all elements from the myArray array to the hidden field name="colors[]". I know the solution to add them as JSON string to the value of the hidden field and then use json_decode in my PHP file to read the array. But the thing is that I have no access to the PHP file and can’t change previously written functions and logic. The PHP file receives an array of checkboxes as it’s usually done in the standard way like:

<input type="checkbox" name="colors[]" value="green">
<input type="checkbox name="colors[]" value="red">
<input type="checkbox name="colors[]" value="yellow">

Is there a way to put myArray in the colors[] array of the hidden input field without using JSON strings and without needing to change anything in the PHP file, so that PHP receives and processes the field colors as a normal array of checkboxes?

Advertisement

Answer

You can add multiple hidden inputs to the form, each with a different value from the array.

$("#myButton").click(function() {
    $("#myForm [name='colors[]']").remove();
    $.each(myArray, function() {
        $("#myForm").append($("<input>", {
            type: "hidden",
            name: "colors[]",
            value: this
        }));
    });
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement