Obtaining values from select multiple

70 views Asked by At

So i have a multi-select which I've adapted with js to work without the CTRL key

$(function(){
    $('.select-toggle').each(function(){    
        var select = $(this), values = {};    
        $('option',select).each(function(i, option){
            values[option.value] = option.selected;        
        }).click(function(event){        
            values[this.value] = !values[this.value];
            $('option',select).each(function(i, option){            
                option.selected = values[option.value];        
            });    
        });
    }); 
});

and i'm using it on multiple input fields, an example below.

<tr class="wide">
   <td class="input titledinput" style="left: -5px;"><select title="Please select the Consoles/Platforms the game is going to be, or has, released on. You can select more than one."
    multiple="multiple" class="select-toggle roundedcorners" name="Consoles" size="1"
    />';
       $qselectconsole = "SELECT * FROM console ORDER BY Console asc";
       $rselectconsole = mysqli_query($dbc, $qselectconsole);
       if(mysqli_num_rows($rselectconsole) !== false){
         while($rowselectconsole = mysqli_fetch_array($rselectconsole, MYSQLI_ASSOC)){
           echo '<option value="'.$rowselectconsole['ConsoleID'].'">'.$rowselectconsole['Console'].'</option>'; 
         }
       } else {
          echo '<option value="0">Something went wrong, please try refreshing the page</option>';
       }
          echo '</select>
   <p2>Platform</p2></td>
</tr>

The multi-select works as expected. Now i would expect $_POST['Consoles'], in this case, to output the value of each selected value. But when i use $_POST['Consoles'] it outputs only the last variable to be selected. How would i go about getting all of the selected values out (as i'll need them later for input to the database).

I am open to a complete rehaul of my JS if needed, i'm an inexperienced javascript programmer and honestly don't really know what i'm doing when it comes to js. I'll learn as i go but if i've done something stupid that means I can only select multiple options but not store each individual value then please let me know.

1

There are 1 answers

3
Marco Mura On BEST ANSWER

First you need to change the name of the var:

name="Consoles"

with:

name="Consoles[]"

This will make possible on php to have all the options into a single "array" now if you on php write:

print_r ($_POST['Consoles']);

You can see each var selected on html page.