Reputation: 3948
I want to achieve this kind of output (fiddler demo) using jQuery UI Autocomplete though.
The only problem with my example is that there is an issue in the arrow key events not like the jquery Autocomplete.
Upvotes: 1
Views: 2483
Reputation: 97
You can try the following jquery plugin we just open sourced in GitHub: https://github.com/tactivos/jquery-sew
Upvotes: 1
Reputation: 2027
I wrote the widget mentioned in this question and have fixed the problem:
http://www.hawkee.com/snippet/9391/
Upvotes: 2
Reputation: 34107
Working demo here: http://jsfiddle.net/cH4p4/ && http://jsfiddle.net/LxpQQ/
Like you mentioned using autocomplete:
"so my textarea output would be "@c#" and the input tag output would be "@[c#]"
HTML
<textarea id='inputbox' placeholder='When @mentions is called its output is put on the input box as well as updated when textarea is blur and submitted'></textarea>
<br/>
<input id="tags" />
<span id="loading" class="hidden">Loading...</span>
Jquery Code
function split(val) {
return val.split(/@\s*/);
}
function extractLast(term) {
return split(term).pop();
}
function getTags(term, callback) {
$.ajax({
url: "http://api.stackoverflow.com/1.1/tags",
data: {
filter: term,
pagesize: 5
},
type: "POST",
success: callback,
jsonp: "jsonp",
dataType: "jsonp"
});
}
$(document).ready(function() {
$("#inputbox")
// 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
$("#tags").val("@["+ui.item.value+"]");
ui.item.value = "@" + ui.item.value;
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);
};
});
CSS
span.count {
font-style: italic;
color: #C0C0C0;
}
.hidden { display: none; }
textarea { width: 300px; height: 100px; resize: none; }
Upvotes: 2