Reputation: 3357
i have a problem i need a hand with here...
I'd like to make an auto-complete field where if one types an "@" they are offered an auto-complete list of names.
I'm using jQueryUI auto-complete and the only problem with my solution ( http://jsfiddle.net/aUfrz/22/ ) is that the autocomplete-able text input needs to be placed on top of the textarea cursor position and not to the right as it currently stands.
Here's my JS that's in the JSFiddle:
$(document.body).on('keypress', 'textarea', function(e) {
var names = [
"johnny",
"susie",
"bobby",
"seth"
],
$this=$(this),
char = String.fromCharCode(e.which);
if(char == '@') {
console.log('@ sign pressed');
var input=$('<input style="position:relative; top:0px; left:0px;background:none;border:1px solid red" id="atSign" >');
$this.parent().append(input);
input.focus();
input.autocomplete({
source: names,
select: function (event, ui) {
console.log('value selected'+ui.item.value);
//$this.val('@'+ui.item.value);
$this.insertAtCaret(ui.item.value);
$this.focus();
input.remove();
} //select
}); //autocomplete
} //if
}); // keypress
HTML:
<textarea></textarea>
Please note that I have NOT shown here a jQuery plugin I used to insert the selected auto-complete suggestion at the caret position: insertAtCaret()
which I found at this other SO question.
Upvotes: 0
Views: 906
Reputation: 1646
There is no cross-browser way to retrieve the on-screen coordinates of a text-area's caret position.
IE has selection objects which I believe you can get X/Y coordinates to place your auto-complete input element - but that will not work on any other browser.
I've never seen a text area widget with an auto complete widget that appeared inline with the text that you are entering - its just not practical to implement, and wouldn't work on all browsers.
You may be able to create a custom rich text editor which uses an iframe using the content editable flag - but that is going to be very difficult to do to ensure that it looks like a regular text area (because copy paste will paste in formatting, which likely you do not want).
Positioning the auto complete box next to the text area (to some side, maybe below it?) seems like your best option here.
Upvotes: 1