Reputation: 16
I am creating an Input box and a submit button after the DOM has loaded but I can't seem to access them after appending
textInput = document.createElement('input');
textInput.setAttribute("id", "myMessage");
textInput.setAttribute("type", "text");
textInput.setAttribute("name", "message");
submitButton = document.createElement('input')
submitButton.setAttribute("id", "sendbutton");
submitButton.setAttribute("type", "submit");
submitButton.setAttribute("name", "submit");
submitButton.setAttribute("value", "Send");
document.getElementById("msgInput").append(textInput)
document.getElementById("msgInput").append(submitButton)
I am trying to access it this way to capture the events keypress
, keyup
and onclick
.
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("myMessage").addEventListener('keypress', handleKeyPress);
document.getElementById("myMessage").addEventListener('keyup', handleKeyUp);
document.querySelector('#sendbutton').onclick = () => {
var data = {'msg': document.querySelector('#myMessage').value, 'username': username };
append_msgs(data);
document.querySelector('#myMessage').value = '';
}
});
Upvotes: 0
Views: 67
Reputation: 86
Try console.log(document.querySelector('#myMessage'))
inside your function, and see what that returns. While it doesn't fix your issue, it might help you use the Inspector Tools (F12 in Chrome) Console in order to figure out what's going on. Have you tried using getElementById
instead of querySelector
for testing purposes?
Upvotes: 1