Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent user from entering decimals?

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 quantities? (Apart from an alert box and setting the field to zero)?

like image 496
hawkeye Avatar asked Sep 02 '11 03:09

hawkeye


1 Answers

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();
    $('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
    $("#singleAdvice").delay(4000).fadeOut(1500);
}
like image 163
jfriend00 Avatar answered Nov 15 '22 19:11

jfriend00