I'm trying to use Select2 (https://select2.github.io) to allow a user to type multiple tags into a field before submitting a form. In my Laravel PHP app, I'll then take those tags, determine if they exist and add them into a database.
My problem is that I can't seem to get Select2 to recognise there are multiple tags being entered by the user. When I interrogate the form data, I only see the LAST tag a user typed as opposed to ALL the tags.
My Select2 element is:
<select class="tags-field" name="tags" data-tags="true" data-placeholder="TAGS" multiple="multiple">
</select>
and my JQuery is:
$(function() {
$(".tags-field").select2({
maximumSelectionLength: 3,
tokenSeparators: [','],
});
}
There are no Javascript errors and it works perfectly fine except I cannot detect ALL the tags.
To cause PHP to make all the selected choices available as an array, suffix your select name with a pair of square brackets, like this:
<select class="tags-field" name="tags[]" data-tags="true" data-placeholder="TAGS" multiple="multiple">
If this form is sent to a PHP program, the value of $_POST['tags'] will be an array. Note that the square brackets in the form control name aren't a part of the array key. You would process such a form like this:
<?php
$tags = $_POST['tags'];
// Note that $tags will be an array.
foreach ($tags as $t) {
echo "$t<br />";
}
?>
References here: http://bbrown.kennesaw.edu/papers/php2.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With