문제

I have been trying to allow numeric field and one decimal point in my Grid.Its work fine when its suitable for input box.

when i am calling onKeyPress the script work fine for "input box" rather than on "Div element"

In "Div element",when i am supposed to use this .It allow to access only for number rather Alphabet

hence,while coming to "decimal place" its not working as it should.[ It's allowing many Dot's]

<script>  
       function getKey(e)  
      {  
        if (window.event)  
           return window.event.keyCode;  
        else if (e)  
           return e.which;  
        else  
           return null;  
      }  
      function restrictChars(e, obj)  
      {  
        var CHAR_AFTER_DP = 2;  // number of decimal places  
        var validList = "0123456789.";  // allowed characters in field  
        var key, keyChar;  
        key = getKey(e);  
        if (key == null) return true;  
        // control keys  
        // null, backspace, tab, carriage return, escape  
        if ( key==0 || key==8 || key==9 || key==13 || key==27 )  
           return true;  
        // get character  
        keyChar = String.fromCharCode(key);  
        // check valid characters  
        if (validList.indexOf(keyChar) != -1)  
        {  
          // check for existing decimal point  
          var dp = 0;  
          if( (dp = obj.value.indexOf( ".")) > -1)  
          {  
            if( keyChar == ".")  
              return false;  // only one allowed  
            else  
            {  
              // room for more after decimal point?  
              if( obj.value.length - dp <= CHAR_AFTER_DP)  
                return true;  
            }  
          }  
          else return true;  
        }  
        // not a valid character  
        return false;  
      }  
    </script>  

<div onKeyPress="return restrictChars(event, this)">

Any Ideas how we could achieve it

도움이 되었습니까?

해결책

For an <input>, it is required to check the value attribute, hence why obj.value is used in your code above. A div element doesn't have a value attribute. You have to check it's innerHTML (mdn docs). If you replace all instances of obj.value with obj.innerHTML, your code should work.

다른 팁

You need to use jQuery keypress() method to handle this right:

$("#d input").keypress(function(event){
    return restrictChars(event);
});

See the working fiddle: http://fiddle.jshell.net/ePvJ8/1/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top