Reputation: 15903
So I'm trying to store the selected <option></option>
tags into an array. I've searched everywhere and can't find any "Good" way of doing it.
<form action='most-liked.php'>
<select multiple name='choose-category' style='display: inline-block;'>
<?php
$allCategories = ["All", "Sport", "Automotive", "Comedy", "Misc"];
$htmlOutput = "";
$i=0;
for($i;$i<sizeof($allCategories);$i++)
{
$htmlOutput .= "<option value='".$allCategories[$i]."'>".$allCategories[$i]."</option>";
}
echo $htmlOutput;
?>
</select>
</form>
I was wondering if there is a way of adding the selected options into the array
on the fly without reloading the whole page...E.g when they choose one of the <option>
's it's value will stored. Im thinking there may be a way of doing this with jQuery
?
I was thinking maybe using a $_GET[]
or something. But not too sure how I'd do it.
Upvotes: 2
Views: 957
Reputation: 2353
you can do like below using jQuery..
<form action='most-liked.php'>
<select id="Category" multiple name='choose-category' style='display: inline-block;'>
<?php
$allCategories = ["All", "Sport", "Automotive", "Comedy", "Misc"];
$htmlOutput = "";
$i=0;
for($i;$i<sizeof($allCategories);$i++)
{
$htmlOutput .= "<option value='".$allCategories[$i]."'>".$allCategories[$i]."</option>";
}
echo $htmlOutput;
?>
</select>
</form>
<script>
var foo = [];
$('#Category').change(function() {
$('#Category :selected').each(function(i, selected){
foo[i] = $(selected).text();
}); alert(foo);
});
</script>
Upvotes: 0
Reputation: 167162
Change the name of the <select>
to:
choose-category[]
So your code will now look like:
<select multiple name='choose-category[]' style='display: inline-block;'>
Also, it is better to avoid -
s in names, so this would be the right one:
<select multiple name='choose_category[]' style='display: inline-block;'>
And you can access it using:
$_REQUEST["choose_category"]
Which gives you an array!
Upvotes: 1
Reputation: 2528
change your select
from
<select multiple name='choose-category' style='display: inline-block;'>
to
<select multiple name='choose_category[]' style='display: inline-block;'>
now your choose_category
is a array and when you will submit it. you will get a post array
with all those values that were selected
Upvotes: 0