Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keyup position using jquery [duplicate]

Tags:

html

jquery

Possible Duplicate:
How to get caret position in textarea?

If i type * in anywhere in the html textarea control i need to get the current position on keyup event like "Welcome* to jQuery". So i have * after Welcome means at 8th position. Let me know if anybody can help me on this.

like image 860
Pradeep Avatar asked Oct 09 '12 07:10

Pradeep


1 Answers

This will work. (note: with quotes it's at 8 else at 7)

$("#tf").on('keyup', function(){
    console.log($(this).val().indexOf('*'));
});​

http://jsfiddle.net/Vandeplas/hc6ZH/

UPDATE: solution with multiple *

$("#tf").on('keyup', function(){
    var pos = [],
        lastOc = 0,
        p = $(this).val().indexOf('*',lastOc);

    while( p !== -1){
        pos.push(p);
        lastOc = p +1;
        p = $(this).val().indexOf('*',lastOc);
    }
    console.log(pos);
});​

http://jsfiddle.net/Vandeplas/hc6ZH/1/

UPDATE: giving only the position of the * char you just typed

(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

$("#tf").on('keypress', function(e){
    var key = String.fromCharCode(e.which);
    if(key === '*') {
        var position = $(this).getCursorPosition();
        console.log(position);
    } else {
        return false;
    }
});​

http://jsfiddle.net/Vandeplas/esDTj/1/

like image 145
VDP Avatar answered Oct 31 '22 11:10

VDP