Allow only numeric value in textbox using Javascript

前端 未结 9 1008
礼貌的吻别
礼貌的吻别 2020-12-19 21:52

I want to allow only numeric values to be entered into the text and if user enters alphabetic character it should warn the user. Any suggestion for optimized and short javas

相关标签:
9条回答
  • 2020-12-19 21:57
    function isNumber(n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    }
    

    from here

    0 讨论(0)
  • 2020-12-19 21:57

    // Solution to enter only numeric value in text box

    $('#num_of_emp').keyup(function () { 
        this.value = this.value.replace(/[^0-9.]/g,'');
    });
    

    for an input box such as :

    <input type='text' name='number_of_employee' id='num_of_emp' />

    0 讨论(0)
  • 2020-12-19 21:57

    or

    function isNumber(n){
      return (parseFloat(n) == n);
    }
    

    http://jsfiddle.net/Vj2Kk/2/

    0 讨论(0)
  • 2020-12-19 21:58

    @Shane, you could code break anytime, any user could press and hold any text key like (hhhhhhhhh) and your could should allow to leave that value intact.

    For safer side, use this:

    $("#testInput").keypress(function(event){
    

    instead of:

    $("#testInput").keyup(function(event){
    

    I hope this will help for someone.

    0 讨论(0)
  • 2020-12-19 22:05

    use following code

    function numericFilter(txb) {
       txb.value = txb.value.replace(/[^\0-9]/ig, "");
    }
    

    call it in on key up

    <input type="text" onKeyUp="numericFilter(this);" />
    
    0 讨论(0)
  • 2020-12-19 22:07

    Javascript For only numeric value in textbox ::

    <input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" /> 
    
    
        <!--Only Numeric value in Textbox Script -->
            <script type="text/javascript">
                function onlyNos(e, t) {
                    try {
                        if (window.event) {
                            var charCode = window.event.keyCode;
                        }
                        else if (e) {
                            var charCode = e.which;
                        }
                        else { return true; }
                        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                            return false;
                        }
                        return true;
                    }
                    catch (err) {
                        alert(err.Description);
                    }
                }
            </script>
            <!--Only Numeric value in Textbox Script -->
    
    0 讨论(0)
提交回复
热议问题