Limit input to numbers and . on input field

前端 未结 3 1134
深忆病人
深忆病人 2021-01-02 10:55

Following on from another question I asked, i really didnt seem to be getting anywhere. Due to my ineptitude. I chose the guys answer because , well he answered my question.

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 11:21

    You could, in the change event of the input, check if the number format is OK. This code will try to get the number and remove anything else: (I'm assuming you use jQuery, if not, please do)

    $('#price').change(function() {
        $(this).val($(this).val().match(/\d*\.?\d+/));
    });
    

    See it working here.

    EDIT: if you don't have jQuery, this code does the same (at least in Chrome):

    document.getElementById('price').onchange = function() {
        this.value = this.value.match(/\d*\.?\d+/);
    };
    

    EDIT 2: not sure if I follow, but you could add this too to prevent letters and other characters before the change event:

    $('#price').keypress(function(event) {
        var code = (event.keyCode ? event.keyCode : event.which);
        if (!(
                (code >= 48 && code <= 57) //numbers
                || (code == 46) //period
            )
            || (code == 46 && $(this).val().indexOf('.') != -1)
           )
            event.preventDefault();
    });
    

提交回复
热议问题