How to make input type number un-editable but still functioning?

前端 未结 3 1807
北荒
北荒 2020-12-22 10:58

I tried this one but not working. is there any way

相关标签:
3条回答
  • 2020-12-22 11:32

    Try this one. It works for me.

    $("#testid").keypress(function (e) {
        e.preventDefault();
    }).keydown(function(e){
        if ( e.keyCode === 8 || e.keyCode === 46 ) {
            return false;
        }
    });
    
    0 讨论(0)
  • 2020-12-22 11:34

    hello I have a working code but i think this is not the best way. I merged the answer from

    How to disable backspace if anything other than input field is focused on using jquery

    and the answer of TuomasK

    here is the working code.

    http://jsfiddle.net/vta96mp1/1/

    HTML

    <input class='testInput' id ='testid' value = '1' name='testname' type='number' min ='1'>
    

    JS

    $("#testid").keypress(function (evt) {
    evt.preventDefault();
    });
    
    $(document).keydown(function(e) {
        var elid = $(document.activeElement).hasClass('textInput');
       console.log(e.keyCode + ' && ' + elid);
        //prevent both backspace and delete keys
        if ((e.keyCode === 8 || e.keyCode === 46) && !elid) {
            return false;
        };
    });
    
    0 讨论(0)
  • 2020-12-22 11:41

    This is from Disable writing in input type number HTML5, but it requires jQuery.

    $("[type='number']").keypress(function (evt) {
        evt.preventDefault();
    });
    

    Without jQuery code is: (input is an input field)

    input.onkeypress=function(evt){
        evt.preventDefault();
    };
    
    0 讨论(0)
提交回复
热议问题