Jquery autocomplete with multiple values from remote JSON - javascript

I want to select multiple values by using the autocomplete()-plugin. The values I do receive from a remote JSON file. So far I can get 1 value but after that it fails. My goal is to select multiple values and store the ID, so I can post the values later on.
So far I have:
<input type="text" id="featured" autocomplete="on"></input>
<input type="hidden" value="" name="artist_id">
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$("#featured").bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}}).autocomplete({
minLength: 0,
source: function( request, response ) {
$.ajax({
url: App.APIO+'/i/search/artist?name='+request.term+'&featured=true',
dataType: "json",
success: function(data) {
var result = $.map(data.data, function(artist) {
return {value: artist.name, label: artist.name, artist_id: artist.artist_id};
});
response( result );
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var item = split( this.value );
// remove the current input
item.pop();
// add the selected item
item.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
item.push( "" );
this.value = item.join( ", " );
return false;
$('[name="artist_id"]').val(ui.item.artist_id); // somehow insert the artist_id here
}
});
Right now I can only enter 1 value and select it, so that it for example displays "Lady Gaga, " but after that I cant enter anything e.g nothing happens. I can see in my network tab that it tries to load
/artist?name=ladygaga%20%b&featured=true
if I forexample type "b" after selecting the first value...
So what am I doing wrong and can someone help me out please...

//At first, Fill in the variable "sourceList" with the json data
var sourceList = $.ajax //to fetch the data
//Create a global variable for accessing the selected values
var selectedItems= [];
//Define the multiselect autocomplete textbox as below :
$("#inputID")
.bind("keydown", function(event) {// don't navigate away from the field on tab when selecting an item
if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) {
event.preventDefault();
}
})
.bind("blur", function(event) {
//var $autoCompleteInstance = $(this).autocomplete("instance");
var selectedObjects = [], currentText = $(this).html();
//if ($autoCompleteInstance.term !== undefined && $autoCompleteInstance.term !== "") {
if (currentText !== undefined && currentText !== "") {
$.each(currentText.split(","), function(index, currentValue) {
var temp = $.grep(sourceList, function(current) {
return current.name === currentValue.trim();
});
$.merge(selectedObjects, temp);
});
selectedItems = selectedObjects;
var valueField = [], textField = [];
$.each(selectedItems, function(i, e) { valueField.push(e.valueField) }); //Resource_Id
$.each(selectedItems, function(i, e) { textField.push(e.textField) });
this.value = valueField.join(", ");
$(this).attr("value", valueField.join(", "));
this.innerHTML = textField.length > 0 ? textField.join(", ") + ", " : "";
}
else {
this.innerHTML = this.value = ""; $(this).attr("value", "");
selectedItems = [];
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(sourceList, extractLast(request.term)));
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
selectedItems.push(ui.item);
var valueField = [], textField = [];
$.each(selectedItems, function(i, e) { valueField.push(e.valueField) }); //Resource_Id
$.each(selectedItems, function(i, e) { textField.push(e.textField) });
this.value = valueField.join(", ");
$(this).attr("value", valueField.join(", "));
this.innerHTML = textField.join(", ") + ", ";
event.preventDefault();
$(this).focus();
placeCaretAtEnd(document.getElementById("attendees"));
//return false;
}
})
.data("ui-autocomplete")._renderItem = function(ul, value) {
return $("<li></li>").data("item.autocomplete", value).append('<span value=' + value.ValueField + '>' + value.TextField + '</span>').appendTo(ul); //Resource_Id
};
Hope this helps :)

Related

Array null not validating in javascript

In my javascript i am trying to check an array if empty.If there is no item in <li> then array will be empty and this should throw error but it is not working. Here is my code
var phrases = [];
$('#listDiv #hiddenItemList').each(function () {
var phrase = '';
$(this).find('li').each(function () {
var current = $(this);
phrase += $(this).text() + ";";
});
phrases.push(phrase);
});
if (phrases === undefined || phrases.length == 0 )
{
$.alert("Please select rate type, high rate and low rate", {
title: "Rates Info",
type: "danger"
});
return false;
}
You have to check that you're not just pushing an empty string into the array. This will make the array phrases have length and not be undefined but won't be what you're looking for.
var phrases = [];
$('#listDiv #hiddenItemList').each(function () {
var phrase = '';
$(this).find('li').each(function () {
var current = $(this);
phrase += $(this).text() + ";";
});
if ( phrase != '' ) {
phrases.push(phrase);
}
});
if (phrases === undefined || phrases.length == 0 )
{
$.alert("Please select rate type, high rate and low rate", {
title: "Rates Info",
type: "danger"
});
return false;
}

Multiselect Detect Option Selected and Deselected On Change

I want to check the if the changed state of a multiselect is deselect or select.
pseudo-code:
$(document).on('change', '.mySelect', function (event) {
if(event === 'selected'){
alert("You have selected this item.");
} else {
alert("You have deselected this item.");
}
});
Something like this doesn't work. How can i check weather the event was a "select" event or a "deselect" event?
EDIT
Here is a jsfiddle DEMO
Try saving the current state of the select element on change:
http://jsfiddle.net/Wexcode/a4mf8akj/5/
function wasDeselected (sel, val) {
if (!val) {
return true;
}
return sel && sel.some(function(d) { return val.indexOf(d) == -1; })
}
$(document).on('change', 'select', function (event) {
var message,
$select = $(event.target),
val = $select.val(),
sel = $('select').data('selected');
// Store the array of selected elements
$select.data('selected', val);
// Check the previous and current val
if ( wasDeselected(sel, val) ) {
message = "You have deselected this item.";
} else {
message = "You have selected this item.";
}
alert(message);
});
The trick is to track the selected options length ..
var $select = $('select');
$select.change(function () {
// Last saved state;
var lastState = $(this).data('total'),
// New state;
changedState = $(this).find('option:selected').length,
txt = (lastState < changedState ?
'selected' : (
lastState > changedState ?
'Deselected' :
'Only one option is selected'));
// save state
$(this).data('total', changedState);
$('#console').append('<p>' + lastState + ' => ' + changedState + '<span>' + txt + '</span></p>');
// Initializing tracker
}).data('total', $select.find('option:selected').length);
Try this here

Multiple jQuery UI mentions autocomplete on the one page

I am having trouble getting multiple mentions autocomplete to work #mention - similar to FB etc.
I have looked on SO and found some good examples on doing a basic mentions autocomplete and have based mine on one, namely:
https://stackoverflow.com/a/17048788/2981412
I am however needing to get it to work across MULTIPLE (....infinite) textareas on the one page rather than just the one (which the above answer does well).
When I add it to more than one (using class selector, rather than ID) the additional ones do not display properly.
See my basic example with dummy data in this fiddle:
http://jsfiddle.net/yv8mn/3/
The top most textarea works fine, but the others show an empty drop down autocomplete menu.
Any ideas?
The JS...
function getCaretPosition (elem) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
elem.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -elem.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (elem.selectionStart || elem.selectionStart == '0')
iCaretPos = elem.selectionStart;
// Return results
return (iCaretPos);
}
function setCaretPosition(elem, caretPos) {
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
function getTags(term, callback) {
var data = {
tags: [
{username: 'john', count: 1}, {username: 'michael', count: 1}
]
};
callback(data);
}
$(document).ready(function() {
$(".appendedInputButton").autocomplete({
source: function(request, response) {
var term = request.term;
var pos = getCaretPosition(this.element.get(0));
var substr = term.substring(0, pos);
var lastIndex = substr.lastIndexOf('#');
if (lastIndex >= 0){
var username = substr.substr(lastIndex + 1);
if (username.length && (/^\w+$/g).test(username)){
getTags(username, function(data) {
response($.map(data.tags, function(el) {
return {
username: el.username,
count: el.count
}
}));
});
return;
}
}
response({});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var pos = getCaretPosition(this);
var substr = this.value.substring(0, pos);
var lastIndex = substr.lastIndexOf('#');
if (lastIndex >= 0){
var prependStr = this.value.substring(0, lastIndex);
this.value = prependStr + '#' + ui.item.username + this.value.substr(pos);
setCaretPosition(this, prependStr.length + ui.item.username.length + 1);
}
return false;
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a>" + item.username+" ("+ item.count+")</a>")
.appendTo(ul);
};
});
The dropdown menus are actually not empty, the list items are just very, very thin. Try clicking on one and you'll see that the information is inserted into the textarea.
So it seems everything works alright, except the styling for some reason.
I found the solution to my problem.
It firstly involved removing the following part of my code from the question:
.data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a>" + item.username+" ("+ item.count+")</a>")
.appendTo(ul);
}
and replacing it with EITHER of these 2 solutions (both fixed it):
$.each($( "ui-autocomplete" ), function(index, item) {
$(item).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a>" + item.username+" ("+ item.count+")</a>")
.appendTo(ul);
};
});
OR
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a>" + item.username+" ("+ item.count+")</a>")
.appendTo(ul);
};
}
Which would then result in the following code (if using the initial solution):
function getCaretPosition (elem) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
elem.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -elem.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (elem.selectionStart || elem.selectionStart == '0')
iCaretPos = elem.selectionStart;
// Return results
return (iCaretPos);
}
function setCaretPosition(elem, caretPos) {
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
function getTags(term, callback) {
var data = {
tags: [
{username: 'john', count: 1}, {username: 'michael', count: 1}
]
};
callback(data);
}
$(document).ready(function() {
$(".appendedInputButton").autocomplete({
source: function(request, response) {
var term = request.term;
var pos = getCaretPosition(this.element.get(0));
var substr = term.substring(0, pos);
var lastIndex = substr.lastIndexOf('#');
if (lastIndex >= 0){
var username = substr.substr(lastIndex + 1);
if (username.length && (/^\w+$/g).test(username)){
getTags(username, function(data) {
response($.map(data.tags, function(el) {
return {
username: el.username,
count: el.count
}
}));
});
return;
}
}
response({});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var pos = getCaretPosition(this);
var substr = this.value.substring(0, pos);
var lastIndex = substr.lastIndexOf('#');
if (lastIndex >= 0){
var prependStr = this.value.substring(0, lastIndex);
this.value = prependStr + '#' + ui.item.username + this.value.substr(pos);
setCaretPosition(this, prependStr.length + ui.item.username.length + 1);
}
return false;
}
});
$.each($( "ui-autocomplete" ), function(index, item) {
$(item).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a>" + item.username+" ("+ item.count+")</a>")
.appendTo(ul);
};
});
});

getting jQuery ui autocomplete to work with #mentions only

I've had a look at a few questions, such as https://stackoverflow.com/a/7222592/2332251
I'm still having trouble reconciling it with the code I have.
At the moment the following works perfectly for searching a username as I start typing.
$(function() {
$("#appendedInputButton").autocomplete({
minLength: 2,
source: "searchusers.php"
});
});
The function in searchusers.php outputs the usernames from the database.
As I said, I'm having trouble making other #mention solutions work for me. I've tried copying over other solutions and swapping my details in but nothing seems to work.
So...
What do I need to do to my current autocomplete script to make it load only
when I initially type the '#' symbol?
I would really like to be able to have multiple #mentions in my posts
(optional) when autocomplete suggests usernames and when I select the username from the list I want it to appear in my post with the #symbol still appended to the front of the username e.g. "hello #john, the # symbol is still attached to your username"
If you need more info, please comment and I will provide more :)
Edit I'm just really unsure of the syntax to make it work. For example, using the example answer I posted above, I came up with (but it doesn't work):
function split(val) {
return val.split(/#\s*/);
}
function extractLast(term) {
return split(term).pop();
}
function getTags(term, callback) {
$.ajax({
url: "searchusers.php",
data: {
filter: term,
pagesize: 5
},
type: "POST",
success: callback,
jsonp: "jsonp",
dataType: "jsonp"
});
}
$(document).ready(function() {
$("#appendedInputButton")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
source: function(request, response) {
if (request.term.indexOf("#") >= 0) {
$("#loading").show();
getTags(extractLast(request.term), function(data) {
response($.map(data.tags, function(el) {
return {
value: el.name,
count: el.count
}
}));
$("#loading").hide();
});
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join("");
return false;
}
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + " <span class='count'>(" + item.count + ")</span></a>")
.appendTo(ul);
};
});
Where do I insert searchusers.php, #appendedInputButton and other specific info? I hope this makes sense.
I will form an answer based on my comments.
First of all lets review the list of requirements:
autocomplete usernames started with # symbol
prepend usernames with # symbol
multiple #mentions in a text
edit any #mention anywhere in a text
to implement the last requirement we need some magic functions that i found on stackoverflow:
getCaretPosition - https://stackoverflow.com/a/2897229/2335291
setCaretPosition - https://stackoverflow.com/a/512542/2335291
Also to detect a username somewhere in the text we need to define some constraints for usernames. I assume that it can have only letters and numbers and test it with \w+ pattern.
The live demo you can find here http://jsfiddle.net/AU92X/6/ It always returns 2 rows without filtering just to demonstrate the behavior. In the listing below i've put the original getTags function from the question as it looks fine for me. Although i have no idea how searchusers.php works.
function getCaretPosition (elem) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
elem.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -elem.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (elem.selectionStart || elem.selectionStart == '0')
iCaretPos = elem.selectionStart;
// Return results
return (iCaretPos);
}
function setCaretPosition(elem, caretPos) {
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
function getTags(term, callback) {
$.ajax({
url: "searchusers.php",
data: {
filter: term,
pagesize: 5
},
type: "POST",
success: callback,
jsonp: "jsonp",
dataType: "jsonp"
});
}
$(document).ready(function() {
$("#appendedInputButton").autocomplete({
source: function(request, response) {
var term = request.term;
var pos = getCaretPosition(this.element.get(0));
var substr = term.substring(0, pos);
var lastIndex = substr.lastIndexOf('#');
if (lastIndex >= 0){
var username = substr.substr(lastIndex + 1);
if (username.length && (/^\w+$/g).test(username)){
getTags(username, function(data) {
response($.map(data.tags, function(el) {
return {
value: el.name,
count: el.count
}
}));
});
return;
}
}
response({});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var pos = getCaretPosition(this);
var substr = this.value.substring(0, pos);
var lastIndex = substr.lastIndexOf('#');
if (lastIndex >= 0){
var prependStr = this.value.substring(0, lastIndex);
this.value = prependStr + '#' + ui.item.value + this.value.substr(pos);
setCaretPosition(this, prependStr.length + ui.item.value.length + 1);
}
return false;
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a>" + item.label + " <span class='count'>(" + item.count + ")</span></a>")
.appendTo(ul);
};
});
I cannot add a comment, so I'm just going to add this as an answer.
I tried the code snippet you've provided and it worked great. The only problem I had was while editing the mention. I decided to edit from the middle of the mention, the autocomplete showed and I selected an item successfully. Only - it didn't delete the rest of the previous mention, only the letters before the cursor's position.
So I added something extra:
select: function(event, ui) {
var pos = comments.init.getCaretPosition(this);
var substr = this.value.substring(0, pos);
var lastIndex = substr.lastIndexOf('#');
var afterPosString = this.value.substring(pos, this.value.length);
var leftovers = afterPosString.indexOf(' ');
if (leftovers == -1)
leftovers = afterPosString.length;
if (lastIndex >= 0){
var prependStr = this.value.substring(0, lastIndex);
this.value = prependStr + '#' + ui.item.value + this.value.substr(pos + leftovers);
comments.init.setCaretPosition(this, prependStr.length + ui.item.value.length + 1);
}
return false;
}
I changed the select function a bit to cover the leftovers. Now, it's searching for the next " " occurrence and adds the length of everything before it to the replaced value.
Hope this helps :)

jQuery - Storing tags using cookies or local Storage using jquerytagbox plugin

I'm trying to save the tags from jQuery TagBox Plugin (from geektantra.com/2011/05/jquery-tagbox-plugin/)
(function(jQuery) {
jQuery.fn.tagBox = function(options) {
var defaults = {
separator: ',',
className: 'tagBox',
tagInputClassName: '',
tagButtonClassName: '',
tagButtonTitle: 'Add Tag',
confirmRemoval: false,
confirmRemovalText: 'Do you really want to remove the tag?',
completeOnSeparator: true,
completeOnBlur: false,
readonly: false,
enableDropdown: false,
dropdownSource: function() {},
dropdownOptionsAttribute: "title",
removeTagText: "X",
maxTags: -1,
maxTagsErr: function(max_tags) { alert("A maximum of "+max_tags+" tags can be added!"); },
beforeTagAdd: function(tag_to_add) {},
afterTagAdd: function(added_tag) {}
}
if (options) {
options = jQuery.extend(defaults, options);
} else {
options = defaults;
}
options.tagInputClassName = ( options.tagInputClassName != '' ) ? options.tagInputClassName + ' ' : '';
options.tagButtonClassName = ( options.tagButtonClassName != '' ) ? options.tagButtonClassName + ' ' : '';
// Hide Element
var $elements = this;
if($elements.length < 1) return;
$elements.each(function(){
var uuid = Math.round( Math.random()*0x10000 ).toString(16) + Math.round( Math.random()*0x10000 ).toString(16);
var $element = jQuery(this);
$element.hide();
try {
var options_from_attribute = jQuery.parseJSON($element.attr(options.dropdownOptionsAttribute));
options = jQuery.extend(options_from_attribute, options);
} catch(e) {
console.log(e);
}
if($element.is(":disabled"))
options.readonly = true;
if( (jQuery.isArray($element)) && $element[0].hasAttribute("readonly") )
options.readonly = true
// Create DOM Elements
if( (options.enableDropdown) && options.dropdownSource() != null ) {
if(options.dropdownSource().jquery) {
var $tag_input_elem = (options.readonly) ? '' : options.dropdownSource();
$tag_input_elem.attr("id", options.className+'-input-'+uuid);
$tag_input_elem.addClass(options.className+'-input');
} else {
var tag_dropdown_items_obj = jQuery.parseJSON(options.dropdownSource());
var tag_dropdown_options = new Array('<option value=""></option>');
jQuery.each(tag_dropdown_items_obj, function(i, v){
if((jQuery.isArray(v)) && v.length == 2 ) {
tag_dropdown_options.push( '<option value="'+v[0]+'">'+v[1]+'</option>' );
} else if ( !jQuery.isArray(v) ) {
tag_dropdown_options.push( '<option value="'+i+'">'+v+'</option>' );
}
});
var tag_dropdown = '<select class="'+options.tagInputClassName+' '+options.className+'-input" id="'+options.className+'-input-'+uuid+'">'+tag_dropdown_options.join("")+'</select>';
var $tag_input_elem = (options.readonly) ? '' : jQuery(tag_dropdown);
}
} else {
var $tag_input_elem = (options.readonly) ? '' : jQuery('<input type="text" class="'+options.tagInputClassName+' '+options.className+'-input" value="" id="'+options.className+'-input-'+uuid+'" />');
}
var $tag_add_elem = (options.readonly) ? '' : jQuery(''+options.tagButtonTitle+'');
var $tag_list_elem = jQuery('<span class="'+options.className+'-list" id="'+options.className+'-list-'+uuid+'"></span>');
var $tagBox = jQuery('<span class="'+options.className+'-container"></span>').append($tag_input_elem).append($tag_add_elem).append($tag_list_elem);
$element.before($tagBox);
$element.addClass("jQTagBox");
$element.unbind('reloadTagBox');
$element.bind('reloadTagBox', function(){
$tagBox.remove();
$element.tagBox(options);
});
// Generate Tags List from Input item
generate_tags_list( get_current_tags_list() );
if(!options.readonly) {
$tag_add_elem.click(function() {
var selected_tag = $tag_input_elem.val();
options.beforeTagAdd(selected_tag);
add_tag(selected_tag);
if($tag_input_elem.is("select")) {
$tag_input_elem.find('option[value="'+selected_tag+'"]').attr("disabled", "disabled");
}
$tag_input_elem.val('');
options.afterTagAdd(selected_tag);
});
$tag_input_elem.keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var this_val = jQuery(this).val();
if(code==13 || (code == options.separator.charCodeAt(0) && options.completeOnSeparator) ) {
$tag_add_elem.trigger("click");
return false;
}
});
if( options.completeOnBlur ) {
$tag_input_elem.blur(function() {
if(jQuery(this).val() != "")
$tag_add_elem.trigger("click");
});
}
jQuery('.'+options.className+'-remove-'+uuid).live( "click", function () {
if(options.confirmRemoval) {
var c = confirm(options.confirmRemovalText);
if(!c) return false;
}
var tag_item = jQuery(this).attr('rel');
if($tag_input_elem.is("select")) {
$tag_input_elem.find('option[value="'+tag_item+'"]').removeAttr("disabled");
}
$tag_input_elem.val('');
remove_tag(tag_item);
});
}
// Methods
function separator_encountered(val) {
return (val.indexOf( options.separator ) != "-1") ? true : false;
}
function get_current_tags_list() {
var tags_list = $element.val().split(options.separator);
tags_list = jQuery.map(tags_list, function (item) { return jQuery.trim(item); });
return tags_list;
}
function generate_tags_list(tags_list) {
var tags_list = jQuery.unique( tags_list.sort() ).sort();
$tag_list_elem.html('');
jQuery.each(tags_list, function(key, val) {
if(val != "") {
var remove_tag_link = (options.readonly) ? '' : ''+options.removeTagText+'';
if((options.enableDropdown) && jQuery('#'+options.className+'-input-'+uuid).find("option").length > 0) {
var display_val = jQuery('#'+options.className+'-input-'+uuid).find("option[value='"+val+"']").text();
} else {
var display_val = val;
}
$tag_list_elem.append('<span class="'+options.className+'-item"><span class="'+options.className+'-bullet">•</span><span class="'+options.className+'-item-content">'+remove_tag_link+''+display_val+'</span></span>');
}
});
$element.val(tags_list.join(options.separator));
}
function add_tag(new_tag_items) {
var tags_list = get_current_tags_list();
new_tag_items = new_tag_items.split(options.separator);
new_tag_items = jQuery.map(new_tag_items, function (item) { return jQuery.trim(item); });
tags_list = tags_list.concat(new_tag_items);
tags_list = jQuery.map( tags_list, function(item) { if(item != "") return item } );
if( tags_list.length > options.maxTags && options.maxTags != -1 ) {
options.maxTagsErr(options.maxTags);
return;
}
generate_tags_list(tags_list);
}
function remove_tag(old_tag_items) {
var tags_list = get_current_tags_list();
old_tag_items = old_tag_items.split(options.separator);
old_tag_items = jQuery.map(old_tag_items, function (item) { return jQuery.trim(item); });
jQuery.each( old_tag_items, function(key, val) {
tags_list = jQuery.grep(tags_list, function(value) { return value != val; })
});
generate_tags_list(tags_list);
}
});
}
})(jQuery);
What I want to do is save the new tags using cookies with jquerycooie.js or using localStorage, but after this:
<div class="row">
<label for="jquery-tagbox-text">Text TagBox (Comma Separated)</label>
<input id="jquery-tagbox-text" type="text" />
</div>
if I add
$.cookie('thetags', 'tags');
and than refresh the page nothing is saved. Any idea or help?
Probably the easiest way to do this would be to use the afterTagAdd callback and (adding) a afterTagRemove callback.
afterTagAdd: function() {
$.cookie('tags', this.get_current_tags_list().join(','));
added_tag();
}
afterTagRemove: function() {
$.cookie('tags', this.get_current_tags_list().join(','));
}
When you load the page, you need to add logic to add all of the cookie-cached values to the tags.
tagBox.add_tag($.cookie('tags'));
All of this is assuming that the separator you passed to TagBox is ','.

Categories

Resources