Shubh Patel
Shubh Patel

Reputation: 3

Javascript not reading single character from input field

I am having a problem in Javascript. In the code below, there are 2 input field with id's "v1" and "v2" respectively. When I try to log the value of input field v1 with only a single character, nothing is shown in the console. After entering the 2nd character, the console shows the first character.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id="v1" /><br>
    <input type="text" id="v2" />

    <script>

        document.getElementById("v1").onkeypress = function() {myFunction()};

        function myFunction() {
            console.log(document.getElementById("v1").value);
            document.getElementById("v1").style.backgroundColor = "red";
         }
    </script>
</body>
</html>

Output:

Output

Upvotes: 0

Views: 537

Answers (1)

Pranav Rustagi
Pranav Rustagi

Reputation: 2721

In place of onkeypress, use onkeyup. The reason why it is not working with onkeypress is because it generates console when the key pressed. Till then, the value has not entered the input field, meaning that it'll give value which is already there. Using onkeyup executes, when the character gets typed in the input field.

document.getElementById("v1").onkeyup = function() {
  myFunction()
};

function myFunction() {
  console.log(document.getElementById("v1").value);
  document.getElementById("v1").style.backgroundColor = "red";
}
<input type="text" id="v1" /><br>
<input type="text" id="v2" />

Upvotes: 1

Related Questions