Search code examples
phpformsselectinnerhtml

form field needs an array


I will get right into it. I have an html page with a select form element tag named "location" and I coded a button to be able to add another select tag form field in case users need to indicate multiple different locations when submitting the form. My problem is I cannot seem to add an additional select form field with a different name="" ideally I would like name="location0" and when user clicks again to add another select form field it should be name="location1" and so on...

I tried the push() function with this code:

<button onclick="add_fields()">Try it</button>

<p id="demo"></p>

<script>
var location= ["location"];
document.getElementById("invoice").innerHTML = location;

function add_fields() {
    location.push("+")
    document.getElementById("invoice").innerHTML = location;
}
</script>

but that did not work either. My implementation of this code is the problem I'm sure.

I provided my code in a js fiddle, the script is included in the html section, only worked in the html section (weird), any help is appreciated, thx.


Solution

  • Put "location[]" as the selects name and then when you receive the data via $_POST, that will be an array with the distinct values.

    If you put something like this, you will see that:

    <?php
    if ($_SERVER['REQUEST_METHOD']==='POST') {
        echo '<pre>';
        print_r($_POST);
        echo '</pre>';
        //$locationArray=$_POST['location'];
    
    }
    ?>
    

    $_POST['location'] will be an array with the distinct values in the distincts positions