I have the following jQuery code:
$('#invitation_emails').on('change', function () {
var tagsArray = $('#invitation_emails')[0].selectize.items;
var lastItem = tagsArray[tagsArray.length - 1];
var emailHelpBlock = $($('.invitation').find('.help-block')[0])
if (!isEmail(lastItem) && !_.isUndefined(lastItem)) {
$('#invitation_emails')[0].selectize.removeItem(lastItem);
if (emailHelpBlock.is(":hidden")) {
emailHelpBlock.show( 'slide', { direction: 'down'});
}
} else {
emailHelpBlock.hide( 'slide', { direction: 'up'});
}
});
Given an array of tags, it checks if the content of a tag is a valid email address. If not, the code removes the tag and should show a help message ONLY if such message is hidden. If the next attempt is an invalid address again the message should stay visible, else it should be hidden.
With this code the message, however, is not displayed correctly in all scenarios. The problem is that when an email is not valid the function removes a tag with the line:
$('#invitation_emails')[0].selectize.removeItem(lastItem);
and this is undesirably regarded as a change. Therefore the function runs again checks the validity of the previous tag, if exists, and shows or hides the message accordingly.
I'd like the function to ignore the change that happens as a result of the removed tag but I can't wrap my head around how to do it. I've tried building a function like:
function remove_tag(e) {
$('#invitation_emails')[0].selectize.removeItem(lastItem);
e.stopPropagation();
}
and executing it instead of the line that removes the tag alone. Don't seem to work out how to use this technique for this purposes though. Any advice?
As @Scaramouche suggested much easier to look for an already available event handler in Selectize plugin. The validation is now performed only when an item is added without causing unexpected issues.
$('#invitation_emails').selectize({
plugins: ['remove_button'],
delimiter: ',',
persist: false,
create: function(input) {
return {
value: input,
text: input
}
},
onItemAdd: function(e){
var itemText = e;
var emailHelpBlock = $($('.invitation').find('.help-block')[0]);
if (!isEmail(itemText) && !_.isUndefined(itemText)) {
$('#invitation_emails')[0].selectize.removeItem(itemText);
if (emailHelpBlock.is(":hidden")) {
emailHelpBlock.show( 'slide', { direction: 'down'});
}
} else {
emailHelpBlock.hide( 'slide', { direction: 'up'});
}
},
});