3

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

1
  • So every keypress you replace the letter 11 times? Commented May 20, 2013 at 0:53

3 Answers 3

3

Try this way:

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

See the working demo.

Sign up to request clarification or add additional context in comments.

1 Comment

Correct and compact. Only thing I'd change is substr to substring, but that's really minor.
1

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/

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.