0

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

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230

1 Answers1

1

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" />
Pranav Rustagi
  • 2,604
  • 1
  • 5
  • 18