jquery only allow input float number

前端 未结 13 1725
既然无缘
既然无缘 2020-12-01 06:28

i\'m making some input mask that allows only float number. But current problem is I can\'t check if multiple dots entered. Can you check those dots and prevent it for me?

13条回答
  •  半阙折子戏
    2020-12-01 07:06

    Using jQuery and allowing negative floats :

    // Force floats in '.js_floats_only' inputs
    $(document).ready(function() {
        $('.js_floats_only').each(function() {
            // Store starting value in data-value attribute.
            $(this).data('value', this.value);
        });
    });
    
    $(document).on('keyup', '.js_floats_only', function() {
        var val = this.value;
        if ( val == '-' ) {
            // Allow starting with '-' symbol.
            return;
        } else {
            if ( isNaN(val) ) {
                // If value is not a number put back previous valid value.
                this.value = $(this).data('value');
            } else {
                // Value is valid, store it inside data-value attribute.
                $(this).data('value', val);
            }
        }
    });
    

提交回复
热议问题