Sep 26, 2024
0
Level 5
Using Select2 as a Tag Like Field to Collect Multiple Email Adresses
I am trying to use Select2 in my laravel project to add emails to a tag like field. Here is my input:
<div class="form-group">
<label for="sendEmails">Send Emails (comma-separated list of VALID email
addresses):</label>
<select id="sendEmails" name="sendEmails[]"
class="form-control select2 @error('sendEmails') is-invalid @enderror"
multiple="multiple">
@if(!empty($settings->sendEmails))
@foreach(explode(',', $settings->sendEmails) as $email)
<option value="{{ $email }}" selected>{{ $email }}</option>
@endforeach
@endif
</select>
<small class="fs-10px text-gray-500-darker">Enter comma-separated email
addresses.</small>
@error('sendEmails')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
</div>
Here is my javascript to initialize the field:
<script>
$(document).ready(function () {
$('#sendEmails').select2({
tags: true, // Allow adding new tags (email addresses)
tokenSeparators: [',', ' '], // Allow comma or space-separated inputs
placeholder: "Enter email addresses",
createTag: function (params) {
var term = $.trim(params.term);
// Validate if it's a valid email format
if (validateEmail(term)) {
return {
id: term,
text: term,
newTag: true
};
}
// If the email is invalid, don't create a tag
return null;
},
insertTag: function (data, tag) {
data.push(tag); // Add valid email tags to the data array
}
});
// Email validation function (basic)
function validateEmail(email) {
var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
});
</script>
It displays the existing values stored in the database as tags as expected. I can also delete and reselect the stage that was deleted. But I cannot seem to add a new email address to the field. There are no errors being generated in the console. What am I missing?
Please or to participate in this conversation.