Using an html file i have created a and and I’m trying get the them to interact using a separate java script file.
I am using the console.log to check if my input is being received and pushed to the console by the button.
This is the body of the HTML file.
const myInput = document.getElementById("myInput");
function guess(myInput) {
console.log(myInput);
}
myInput.addEventListener("click", document.getElementById("myInput"))
<h1 id="random">Random Number guesser</h1>
<h2>Guess a number below between 1 - 100.</h2>
<div>
<button id="button" onclick="guess()">Guess!</button>
<input id="myInput" type="text">
</div>`your text`
<script src="config.js"></script>
3
Answers
This could be a goo starting point. When clicking the button the form will submit. The default behaviour is to reload the page — you don’t want that, therefore
e.preventDefault()
. Now you can get the value by the name of the input:i did not get your question what are you really trying to say but which i get that you trying to print the value of input box in console so here is the full page code
On execution, your guess function does not accept any arguments. Lucky for us, we can access
myInput
in our JS file. Just by removing the myInput parameter from theguess()
function, we can solve the problem. Which also renders theeventListener
useless.eventListener
is also wrong. The second argument of theeventListener
is a callback function. Refer to the MDN docs for better explanation. Below is your code fixed to use theeventListener
instead of theguess()
function.You don’t need to use both
onclick
attribute and theeventListener
in this case.