How to prevent user from entering decimals?

后端 未结 3 1053
北恋
北恋 2020-12-19 04:02

I\'ve got an order page on my site. Some order items can have decimal quantities, some can\'t.

What\'s the best way to prevent the user from entering decimal quanti

3条回答
  •  Happy的楠姐
    2020-12-19 04:24

    Intercept key events for the field, detect illegal characters upon input, keep them from getting entered in the field and add a temporary msg near the field (inserted into the page) that explains what characters or values are allowed. pop up alerts are a bad way to give feedback in the middle of typing.

    Then, validate again before submission because there are other ways to get data into fields (drag/drop, copy/paste, etc...) that you might not have caught everything.

    Here's a jQuery example of both an integer only and a decimal only field with temporary messages displayed when invalid keys are typed:

    Working jsFiddle: http://jsfiddle.net/jfriend00/CkDTy/

    $(".integer").keypress(function(e) {
        if (e.which < 48 || e.which > 57) {
            showAdvice(this, "Integer values only");
            return(false);
        }
    });
    
    $(".decimal").keypress(function(e) {
        // 46 is a period
        if (e.which != 46 && (e.which < 48 || e.which > 57)) {
            showAdvice(this, "Decimal numbers only");
            return(false);
        }
        if (e.which == 46 && this.value.indexOf(".") != -1) {
            showAdvice(this, "Only one period allowed in decimal numbers");
            return(false);   // only one decimal allowed
        }
    });
    
    function showAdvice(obj, msg) {
        $("#singleAdvice").stop(true, false).remove();
        $('' + msg + '').insertAfter(obj);
        $("#singleAdvice").delay(4000).fadeOut(1500);
    }
    

提交回复
热议问题