0

I want user to restrict user that they can only enter two digit after decimal. but they can also remove the entered digits using space key. I have following code but its not allowing me to remove the entered digits using space Like:

Suppose I have entered : 5454645.54 now if user will move cursoe on text box and want to remove these digits its not allowing user to do so. Please advice which correction need to do for this in following code:

function restrictUser(el, evt) {  
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var number = el.value.split('.');
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))     {
        return false;
    }

    if(number.length>1 && charCode == 46){
         return false;
    }
    var caratPos = getSelectionStart(el);
    var dotPos = el.value.indexOf(".");
    if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
        return false;
    }
     return true;
}
function getSelectionStart(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveEnd('character', o.value.length)
        if (r.text == '') return o.value.length
        return o.value.lastIndexOf(r.text)
    } else return o.selectionStart
}

Thanks Advance.

Sunil Rawat
  • 709
  • 10
  • 41

0 Answers0