In my page, I've added an onkeyup
event in order to get the keys that have been pressed in my input
.
I get the results in my console, but I need to output all the events as a single JSON
output and return
it.
I'm new in JS
and any help is appreciated
PS: For some reason my snippet doesn't work here, but in my index.html
I can see the event output fine.
window.onload = function() {
const myInput = document.getElementById('myInput');
myInput.onkeyup = function(e) {
console.log(e);
}
}
<input type="text" value="" id="myInput">
The screenshot below is what I get in return:
Current output:
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
And what I'm looking for is to be able to assign this to a variable, like var json
and output would be something as:
{
"onkeyup":
"{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}"
}
Thanks in advance!
Okay, first things first:
The output sample you gave us is not valid in any JSON specification and don't evaluate as a object in JavaScript (because of the wrong use of quotes).
What you want instead is an object with a property "onkeyup" (the name of event handled) that holds an array of objects (in your case, the ocurrences of this event).
let obj = { onkeyup: [] };
window.onload = function() {
const myInput = document.getElementById('myInput');
myInput.onkeyup = function(e) {
obj.onkeyup.push(e);
console.log( obj );
}
}
This might solve your problem by having and object with the structure desired that you can actually update and use as you want further on your code.