简体   繁体   中英

Keep barcode scanner but disable Keyboard in HTML textbox

i have a html page and want to disable keyboard entries, only bar-code scanner entries should allow. Thanks in advance

Your code is wrong, e.which / e.keyCode always return numbers.

you need to check the bounds of those numbers or check new value of input.

var tb=document.getElementById('textbox1');
tb.onkeypress = function(e) {
       e = e || window.event;
       var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
       if (charCode < 48 || charCode > 57) {
           return false;
       }
    };

An easier way will be to use:

<input type="number" id="textbox2">

here is a fiddle that works with both methods: http://jsfiddle.net/vgx4unc7/

Check out this jQuery function:

$(document).ready(function() {
    var pressed = false; 
    var chars = []; 
    $(window).keypress(function(e) {
        if (e.which >= 48 && e.which <= 57) {
            chars.push(String.fromCharCode(e.which));
        }
        console.log(e.which + ":" + chars.join("|"));
        if (pressed == false) {
            setTimeout(function(){
                if (chars.length >= 10) {
                    var barcode = chars.join("");
                    console.log("Barcode Scanned: " + barcode);
                    // assign value to some input (or do whatever you want)
                    $("#barcode").val(barcode);
                }
                chars = [];
                pressed = false;
            },500);
        }
        pressed = true;
    });
});
$("#barcode").keypress(function(e){
    if ( e.which === 13 ) {
        console.log("Prevent form submit.");
        e.preventDefault();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM