John Smith
John Smith

Reputation: 495

Trouble with my code, I have a "-" which has to be inserted on each Enter key

I have some trouble with my code, I have a "-" which has to be inserted on each Enter key, here's my jQuery, and jsfiddle:

$("#textbox").on("keydown", function(e) {
      if(e.which == 13){
        var $this = $(this);
        setTimeout(function(){
          $this.insertAtCaret("- ");
        }, 0);
      }

http://jsfiddle.net/npGVS/

Thanks in advance :)

Upvotes: 0

Views: 73

Answers (1)

Andy
Andy

Reputation: 14575

insertAtCaret is an extension to jQuery and not normally in it. If you add in the extension, it works:

DEMO

$.fn.insertAtCaret = function(myValue) {
    return this.each(function() {
        var me = this;
        if (document.selection) { // IE
            me.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
            me.focus();
        } else if (me.selectionStart || me.selectionStart == '0') { // Real browsers
            var startPos = me.selectionStart, endPos = me.selectionEnd, scrollTop = me.scrollTop;
            me.value = me.value.substring(0, startPos) + myValue + me.value.substring(endPos, me.value.length);
            me.focus();
            me.selectionStart = startPos + myValue.length;
            me.selectionEnd = startPos + myValue.length;
            me.scrollTop = scrollTop;
        } else {
            me.value += myValue;
            me.focus();
        }
    });
};

Upvotes: 3

Related Questions