Remove key pressed in an input text

Asked

Viewed 1,220 times

2

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

What I’m doing is, I use the keydown in input, step the event of the key:

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

Now in function js is that I’m not quite sure what to do. I can tell which key to press with the e.which, now erase is I’m not seeing how it’s done.

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

  • It’s like you gave a Backspace input?

  • That’s exactly what @Felipeavelar looks like

  • @Gustavorodrigues, as I confirmed to Felipe Avelar what I want is: Give Backspace when the user inserts a character. Placeholder is no close solution to this. Also because if you want to copy the content of the input, and use the placeholder is absolutely impossible

  • If the goal is to not let the user edit the input, it would not be easier to simply use the attribute readonly?

  • @Kazzkiq, yes I could use the readonly. The issue is sometimes clients who demand certain "things" like this :/ But it’s already solved :)

3 answers

6

Do so:

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: http://jsfiddle.net/3ZwF4/2/

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

  • Exactly what I was looking for! Thank you

2

You could simply prevent the action of the key by returning false:

jsfiddle

Code:

$("#foo").on("keydown", function (e) {
    if (e.keyCode >= 32)
        return false;
});
  • Your solution is interesting, however it accepts that I delete the characters using backspace or add new characters using alt + numero (ex.: alt + 155)

  • These cases would have to be added to the condition that returns false. I’m going to improve on that!

2


HTML-only solution (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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.