0

If I had an input field like so for example:

<input id="inputBox" type="text">

And the user enters 'abc' for example, how can I change this immediately to '123'? I want this to happen as soon as soon as the user enters 'abc'.

How can I do this?

4
  • 1
    Have you tried anything so far? Commented Mar 15, 2018 at 18:51
  • 2
    bind onkeyup or onkeydown Commented Mar 15, 2018 at 18:51
  • @Phiter I didn't know how to go about detecting the text changes, so no Commented Mar 15, 2018 at 18:54
  • @Sphinx I see, thank you. Commented Mar 15, 2018 at 18:54

4 Answers 4

3

Hope this will help you, use keyup event to get entered value

 $("#inputBox").on("keyup", function(){
      if($(this).val() == "abc")
         $(this).val("123");
    })
Sign up to request clarification or add additional context in comments.

2 Comments

Ideally, some explanation would be given.
@Devaffair correct i have added short explanation to use keyup event to get entered value
1

You could do something like this:

HTML:

<input id="inputBox" type="text">

JS/jQuery:

$(document).on('keydown', '#inputBox', function(){
$(this).val("Your new value");
return false;
});

https://jsfiddle.net/j0ug8y3e/

There is a 'change' event on jQuery, but it's only called when the input has lost it's focus, so using a keydown, keypressed or keyup is better.

1 Comment

This answer is much more elaborated. please just change $("#inputBox") to $(this) and it's perfect.
0
$( "#inputBox" ).keyup(function() {
  if($(this).val() == "abc") {
        $(this).val("123");
  }
});

Comments

0

This is the full solution, it will convert each letter to its numerical value as you type:

const input = $('#inputBox');
input.keyup(event => {
    input.val(processContents(input.val()));
});
function processContents(value) {
    let contents = value.split('');
    contents.forEach((char, index) => {
        var charPos = char.toLowerCase().charCodeAt(0);
        console.log(charPos);
        if (charPos >= 97 && charPos <= 122) {
            contents[index] = charPos - 96;
        }
    });
    return contents.join('');
}

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.