0

I have a textbox, where a forbidden character cant be typed. #.

This works, however, when the textbox is filled in with data, and I put the focus on the middle of the textbox and then I use the arrow keys to go left and right, then it jumps to the end of the textbox.

If I type a character also in the middle of the textbox, it goes to the end again

$('[id$=txtClient]').keyup(function () {
        EnableClientValidateButton(); // When the textbox changes, the user has the ability to validate the client
        ChangeColorClient("0"); // The color is changed to white, to notify the user the client is not validated yet.
        var $el = $('[id$=txtClient]'); // the text element to seach for forbidden characters.
        var text = $el.val(); // The value of the textbox
        text = text.split("#").join("");//remove occurances of forbidden characters, in this case #
        $el.val(text);//set it back on the element
    });
Luis Valencia
  • 32,619
  • 93
  • 286
  • 506

5 Answers5

3

Javascript allows you to set the cursor position for inputs.

I found two useful functions:

And the solution could look like this:

  function getCaretPosition (elem) {

    // Initialize
    var iCaretPos = 0;

    // IE Support
    if (document.selection) {

      // Set focus on the element
      elem.focus ();

      // To get cursor position, get empty selection range
      var oSel = document.selection.createRange ();

      // Move selection start to 0 position
      oSel.moveStart ('character', -elem.value.length);

      // The caret position is selection length
      iCaretPos = oSel.text.length;
    }
    // Firefox support
    else if (elem.selectionStart || elem.selectionStart == '0')
      iCaretPos = elem.selectionStart;

    // Return results
    return (iCaretPos);
  }

  function setCaretPosition(elem, caretPos) {
      if(elem != null) {
          if(elem.createTextRange) {
              var range = elem.createTextRange();
              range.move('character', caretPos);
              range.select();
          }
          else {
              if(elem.selectionStart) {
                  elem.focus();
                  elem.setSelectionRange(caretPos, caretPos);
              }
              else
                  elem.focus();
          }
      }
  }

$('[id$=txtClient]').keyup(function () {
    EnableClientValidateButton(); // When the textbox changes, the user has the ability to validate the client
    ChangeColorClient("0"); // The color is changed to white, to notify the user the client is not validated yet.
    var $el = $('[id$=txtClient]'); // the text element to seach for forbidden characters.
    var text = $el.val(); // The value of the textbox
    text = text.split("#").join("");//remove occurances of forbidden characters, in this case #

    var pos = getCaretPosition(this);
    $el.val(text);//set it back on the element
    setCaretPosition(this, pos);
});
Community
  • 1
  • 1
claustrofob
  • 5,448
  • 2
  • 19
  • 22
1

This is a bit unpleasant, and I'm not 100% happy, but it solves all the given issues that you've had...

$("[id$=txtClient]").keyup(function (e) {
    var text = $(this).val();
    if (text.indexOf("#") > -1) {
        text = text.replace("#", "");
        $(this).val(text);
    }
});

Here's a jsFiddle example...

http://jsfiddle.net/E4cBK/

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
1

Have you tried using the keypress event ?

The documentation warns about possible differences in behavior between platforms.

In Firefox at least, e.which corresponds to the ascii code of the typed character after transformation :

$('#txtClient').keypress(function (e) {
    console.log('keypress:', e.which);
    if (e.which == 35) {
        return false;
    }
});

updated fiddle

LeGEC
  • 46,477
  • 5
  • 57
  • 104
  • unfortunately the cursor is still jumping when trying to insert the `#` in the middle. I guess you cannot solve this easily as claustrophobs proposed answer is good, but the CaretPosition is not supported by all browsers. – Christoph Jun 19 '13 at 11:01
0

You can prevent to execute your code if the user presses a right or a left arrow. To do this you just need to add this condition:

if(e.which != 37 && e.which != 39){  

You can find the key codes here.

Your full code would be:

$('[id$=txtClient]').keyup(function () {
    if(e.which != 37 && e.which != 39){  
        EnableClientValidateButton();
        ChangeColorClient("0"); 
        var $el = $('[id$=txtClient]'); 
        var text = $el.val(); 
        text = text.split("#").join("");
        $el.val(text);//set it back on the element
    }
});

LIVING EXAMPLE

Alvaro
  • 40,778
  • 30
  • 164
  • 336
0

Just prevent the default action on keypress(keydown does not give consistent charCodes):

$('[id$=txtClient]').keypress(function (e) {
        if (String.fromCharCode(e.which) == '#'){
            e.preventDefault();
        }
});

This just prevents # and leaves the rest as it is.

Here you go;)

Christoph
  • 50,121
  • 21
  • 99
  • 128