Trying to create keydown events using the below snippet. The keypress function triggers, but the value is not added to the textbox. I want to edit value of textbox 1 using the keys.
fyi - Purposely avoiding setting element.value directly
<html>
<head>
<script>
function f1() {
document.querySelector("#text1").focus()
document.querySelector("#text1").onkeydown = test;
var keypress = new KeyboardEvent("keydown", {
key: "e",
keyCode: 69, // example values.
code: "KeyE", // put everything you need in this object.
which: 69,
shiftKey: false, // you don't need to include values
ctrlKey: false, // if you aren't going to use them.
metaKey: false // these are here for example's sake.
})
console.log("srcElement" + keypress.srcElement);
console.log("currentTarget" + keypress.currentTarget);
var element = document.getElementById("text1")
element.dispatchEvent(keypress);
console.log("srcElement" + keypress.srcElement);
console.log("currentTarget" + keypress.currentTarget);
}
function test(e) {
console.log("Called" + e.key);
console.log("Called" + e.keyCode);
}
</script>
</head>
<body onload="f1()">
<form>
Input 1 : <input type="text" id="text1" name="text1" />
Input 2 :<input type="text" id="text2" name="text2" />
</form>
</body>
</html>
Here is the output on console:
test.html:17 srcElementnull
test.html:18 currentTargetnull
test.html:25 Callede
test.html:26 Called69
test.html:21 srcElement[object HTMLInputElement]
test.html:22 currentTargetnull