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; }
?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…