Remove key pressed in an input text

2

I have the following scenario: A input text that comes with a certain value / text from the DB but that the user should not be able to edit. To do this, pressing a key on input will delete that same character.

What I'm doing is: I use keydown on input , I pass the key event:

<input type="text" value="Texto da base de dados" keydown="apagaLetra(this)" />

Now in the js function, I'm not sure what to do. I can see which key is pressed with e.which , now delete is that I am not seeing how it is done.

The end result is: When the user presses a key in the input, from the JS I do backspace

    
asked by anonymous 11.03.2014 / 12:49

3 answers

2

Solution only with HTML ( readonly ):

<input type="text" value="Texto da base de dados" readonly />

Solution in javascript (jquery):

function travarInput(el){
    var v = el.val();
    el.on('keyup',function(){
       el.val(v); 
    });
}

Example of both: FIDDLE

    
11.03.2014 / 15:09
6

Do this:

HTML:

<input id="foo" value="banco de dados">

JS:

var keydown = function(e) {    
    var $this = $(this);
    var valor_antigo = $this.val();

    $this.off("keydown");
    $this.on("keydown", function(){
        return false;    
    });

    $this.on("keyup", function(evt) {
         $this.val(valor_antigo);
         $this.off("keyup");

         $this.off("keydown");
         $this.on("keydown", keydown);
    });    
};

$("#foo").on("keydown", keydown);

Take a look at this fiddle: link

The code is a bit complex because it is necessary to prevent when the user presses a key and holds.

    
11.03.2014 / 13:10
2

You could simply prevent the key action from returning false:

jsfiddle

Code:

$("#foo").on("keydown", function (e) {
    if (e.keyCode >= 32)
        return false;
});
    
11.03.2014 / 14:42