2

Hi how to disable delete key press or backspace key press when deleting a particular character from a string using jQuery. For example, from string 1234-555 when the cursor is at hypen, if delete key is pressed it should not delete hypen. Instead of that cursor should stay in the same position. Basically disabling the delete key at hyphen. In the same way when the cursor is after hypen, if backspace key is pressed it should not delete hypen. Instead of that cursor should stay in the same position.

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
wiki
  • 2,543
  • 4
  • 19
  • 11
  • you can try viewing these plugins: http://digitalbush.com/projects/masked-input-plugin/ and http://www.meiocodigo.com/projects/meiomask/ – andres descalzo Nov 26 '10 at 04:55

1 Answers1

1

Sure, use the keydown event.

EDIT: to get the current position of the cursor in a text box, you will need to use the following function (provided by @CMS no less):

function getCaret(el) { 
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length; 
  }  
  return 0; 
}

Now, back to my original answer:

var nobackspace = ['-'];
$(element).keydown(function(e) {
   if(e.keyCode == 8) {//backspace key was pressed
    var pos = getCaret(this);

    if(pos > 0) pos--;  //just a precaution so we don't get a negative number

    if(!jQuery.inArray($(this).val().charAt(pos), nobackspace)) return false;
   }
});

jsFiddle example

Community
  • 1
  • 1
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • That function may be from CMS, but it only deals with collapsed selections and will not handle empty lines properly in IE. I've posted copies of a superior function all over SO. – Tim Down Nov 26 '10 at 09:25