0

I want after type two number in filed append / and set cursor in home.

My mean of the home is, Home key on the keyboard : enter image description here

I try as: (In my code instead run Home key this adding $)

<input type="text" class="num" maxlength="2"/>
​
$(".num").keypress(function(e){
    var val = this.value;
    var value =  val + String.fromCharCode('36');
    (val.length == '2') ? $(this).val(value+'/') : '';
});​

DEMO: http://jsfiddle.net/3ePxg/

How can done it?

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Taylor Gomez
  • 320
  • 1
  • 5
  • 22

2 Answers2

0

When 2 is entered in the input we can append / and go to the beginning (left side) of input field with this: I don't follow with the Home key -- what do you want to happen with that (if you mean put the cursor at the start of the input field look at this)? However, with the keypress event of 2 to be 2/ we can do:

$(".num").on('keypress', function(e){
    if (e.keyCode == 50) {
        var input = $(e.target);
        input.val(input.val() + '2/');
        input.focus();
        e.target.setSelectionRange(0,0);
    }
});​

Demo: jsfiddle

Community
  • 1
  • 1
Cymen
  • 14,079
  • 4
  • 52
  • 72
0

try this:

js:

//based on script from here: http://stackoverflow.com/a/4085357/815386 -> http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea
function setCaretPosition(ctrl, pos) {
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos, pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

function GetCaretPosition(ctrl) {
    var CaretPos = 0; // IE Support
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0') CaretPos = ctrl.selectionStart;
    return (CaretPos);
}

$(".num").keyup(function(e) {
    var val = this.value;
    if (val.length >= '2') {
        var value = val.substr(0, 2);
        var pos=GetCaretPosition(this);
        $(this).val(value + '/');
        setCaretPosition(this, pos);
        console.log(GetCaretPosition(this));
        if (pos >= 2) {
            setCaretPosition(this, 0);
            return false;
        }
    }
});​

DEMO

zb'
  • 8,071
  • 4
  • 41
  • 68
  • What you mean by "How is it summarized?" ? About large codes... all my code and fixed your in `keyup` handler, the GetCaretPosition and setCaretPosition are 3rd party code – zb' Dec 07 '12 at 18:02