Hey everyone! I’m trying to figure out how to make a button do something when it’s clicked, but I want to do it all in JavaScript instead of using HTML. I’ve tried using an event listener, but it’s not working for some reason. Here’s what I’ve got so far:
let submitBtn = document.querySelector('#submitBtn');
let nameInput = document.querySelector('#nameInput');
let messageInput = document.querySelector('#messageInput');
submitBtn.addEventListener('click', handleSubmit);
function handleSubmit() {
let result;
if (nameInput.value === 'admin' && messageInput.value === 'password') {
result = 'Access granted';
} else {
result = 'Please enter correct credentials';
}
document.querySelector('#outputArea').textContent = result;
}
Can someone help me figure out what I’m doing wrong? Thanks!
yo man, ur codes lookin good! but maybe try addin some console.log() statements in ur handleSubmit function. that way u can see if its actually bein called when u click the button. also, make sure ur html has all the right IDs. sometimes its the little things that trip us up!
Your approach is sound, but there might be a timing issue. Consider wrapping your code in a DOMContentLoaded event listener to ensure all elements are loaded before your script runs:
document.addEventListener('DOMContentLoaded', function() {
let submitBtn = document.querySelector('#submitBtn');
// ... rest of your code ...
});
Also, double-check your HTML to ensure all IDs match exactly. If issues persist, try using console.log() within your event listener to confirm it’s being triggered. Lastly, verify that your script is properly linked in your HTML file. These steps should help isolate and resolve the problem.
I’ve been in your shoes, and I can tell you that your code looks pretty solid! The issue might not be in the JavaScript itself, but in how it’s connected to your HTML.
Make sure your HTML elements have the correct IDs that match what you’re querying in your JavaScript. For example, check if you have elements with IDs ‘submitBtn’, ‘nameInput’, ‘messageInput’, and ‘outputArea’ in your HTML.
Also, ensure your script is loaded after the DOM is ready. You can do this by either placing your script tag at the end of the body, or wrapping your code in a DOMContentLoaded event listener.
If it’s still not working, try adding some console.log() statements in your handleSubmit function to see if it’s being called at all. This can help pinpoint where the issue might be.
Remember, debugging is part of the process. Keep at it, and you’ll figure it out!