Jamal.Eddi
Jamal.Eddi

Reputation: 53

Replace input in real time with jQuery

I have a problem with this script, I want to replace anything entered in the input field with a specific letter in real time, with Hello World in the field.

 <input id="inputID" type="text" value="" maxlength="11"/>
 $('#inputID').keyup(function(e){
  var cv=["h","e","l","l","o"," ","w","o","r","l","d",""];

  var i=$('#inputID').val();

  for (j=0;j<11;j++){

    this.value = this.value.replace(i[j],cv[j]);

}

});

This script works well when I write slowly but not when I write quickly. thanks for your help

Upvotes: 3

Views: 137

Answers (3)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107626

This is about as fast as I could get it with maintaining the event on keyup:

var hw = "hello world";
$('#inputID').keyup(function(e){
    this.value = hw.substring(0, this.value.length);
});

Demo

Edit: I'm fairly amazed that three people came up with nearly the exact same solution. Really cool.

Edit 2: I tweaked it a bit to make it replace the character initially typed with a space to help lessen the effect of the letters being replaced.

var hw = "hello world";
$('#inputID').keydown(function (e) {
    if (e.which !== 8) { // allow backspace
        e.preventDefault();
        this.value += ' ';
    }
}).keyup(function () {
    this.value = hw.substring(0, this.value.length);
});

Second demo

Upvotes: 0

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

xdazz's solution is correct (he beat me to it)

I figured there might be benefit in showing a solution that does not rely on jQuery at all, so users who don't want to rely on it can benefit too.

 document.getElementById('inputID').onkeyup = function () {
     var cv = "hello world"; // Your 'correct value' 
     //Set the value to a substring of cv at the current length
     this.value = cv.substring(0, this.value.length); 
 };

http://jsfiddle.net/9yfCe/

Upvotes: 1

xdazz
xdazz

Reputation: 160973

Try this way:

$('#inputID').keyup(function(e){
     var cv = 'hello world';
     this.value = cv.substr(0, this.value.length);
});

See the working demo.

Upvotes: 3

Related Questions