Select2 - Multiple tags do not work

I am trying to use Select2 ( https://select2.imtqy.com ) to allow the user to enter multiple tags in the field before submitting the form. In my Laravel PHP application I will take those tags, determine if they exist and add them to the database.

My problem is that I cannot get Select2 to recognize that the user is entering multiple tags. When I interrogate form data, I see only the LAST tag that the user entered, and not ALL tags.

My Select2 element:

<select class="tags-field" name="tags" data-tags="true" data-placeholder="TAGS" multiple="multiple"> </select> 

and my jquery:

 $(function() { $(".tags-field").select2({ maximumSelectionLength: 3, tokenSeparators: [','], }); } 

There are no Javascript errors, and it works great, but I cannot detect ALL tags.

+4
source share
2 answers

To force PHP to make all selections available as an array, suffix your selection name with a pair of square brackets, for example:

 <select class="tags-field" name="tags[]" data-tags="true" data-placeholder="TAGS" multiple="multiple"> 

If this form is submitted to a PHP program, the value of $ _POST ['tags'] will be an array. Note that the square brackets in the form control name are not part of the array key. You would process this form as follows:

 <?php $tags = $_POST['tags']; // Note that $tags will be an array. foreach ($tags as $t) { echo "$t<br />"; } ?> 

Links here: http://bbrown.kennesaw.edu/papers/php2.html

+6
source
  • use hidden input field to send all values
  • use the onsubmit event to set the value of the hidden field

HTML:

 <form method="post" action="post.php"> <select multiple id="e1" style="width:300px" name="_state"> <option value="AL">Alabama</option> <option value="Am">Amalapuram</option> <option value="An">Anakapalli</option> <option value="Ak">Akkayapalem</option> <option value="WY">Wyoming</option> </select> <input type="hidden" name="state" value="" /> <input type="submit"/> </form> 

JQ:

 $("#e1").select2(); $('form').submit(function () { var newvalue = ''; var value = $('select[name="_state"]').val(); if (value) { newvalue = value; } $('input[name="state"]').val(newvalue); }) 
+1
source

All Articles