How to prevent user from typing in text field without disabling the field?

前端 未结 11 1693
不思量自难忘°
不思量自难忘° 2021-01-31 06:58

I tried:

$(\'input\').keyup(function() {

   $(this).attr(\'val\', \'\');

});

but it removes the entered text slightly after a letter is enter

11条回答
  •  不知归路
    2021-01-31 07:29

    I like to add one that also works with dynamic javascript DOM creation like D3 where it is impossible to add:

    //.attr(function(){if(condition){"readonly"]else{""}) //INCORRECT CODE !
    

    to prevent actions on a HTML input DOM element add readonly to class:

    var d = document.getElementById("div1");
    d.className += " readonly";
    

    OR in D3:

     .classed("readonly", function(){
       if(condition){return true}else{return false}
     })
    

    AND add to CSS or less:

    .readonly {
      pointer-events: none;
    }
    

    the nice thing about this solution is that you can dynamically turn it on and of in a function so it can be integrated in for example D3 at creation time (not possible with the single "readonly" attribute).

    to remove the element from class:

    document.getElementById("MyID").className =
      document.getElementById("MyID").className.replace(/\breadonly\b/,'');
    

    or use Jquery:

    $( "div" ).removeClass( "readonly" )
    

    or toggle the class:

    $( "div" ).toggleClass( "readonly", addOrRemove );
    

    Just to be complete, good luck =^)

提交回复
热议问题