pretty new to coding. But I have a small assignment where I just not get what function I should do or how I should write it down. Basicly it should give an input box and a button (this works). But now I want to give an alert IF the input is hi and a different alert if the input is bye. For all other inputs there shouldn't happen anything. I'm just not getting it, can someone help out?
<h1>Welcome</h1>
Input: <input id="welcome1" type="text" />
<button id="button">Click here</button>
</body>
<script type="text/javascript">
if (document.getElementById("welcome1").textContent = "hi"){
document.getElementById("button").onclick = alert("Welcome");
}
else (document.getElementById("welcome1").textContent = "bye"){
document.getElementById("button").onclick = alert("See you later");
}
</script>
You should add an event listener to the button, but first you should identify it.
To identify it, you have to use document.getElementById("the_id"). Keep in mind that we have other ways to find the element, in other words, we have many selectors (id, class, tag name, etc.).
And when you use an else statement, you do not specify another condition. To specify other condition you have to use else if, because else is for anything that was not in the if or an else if.
<h1>Welcome</h1>
Input: <input id="welcome1" type="text" />
<button id="button">Click here</button>
<script type="text/javascript">
const btn = document.getElementById("button")
btn.addEventListener("click", function() {
if (document.getElementById("welcome1").value === "hi") {
alert("Welcome");
} else {
alert("See you later");
}
})
</script>
Input: <input id="welcome1" type="text" >
<button id="button">Click here</button>
<script type="text/javascript">
// add eventListener to the element
document.querySelector("#button").addEventListener("click", handleButton, false)
// function handle to check
function handleButton () {
// get the value from the input
// use querySelector instead of getElementById
const inputText = document.querySelector("#welcome1").value;
// check if is the same string and the same type (string)
if(inputText === "hi") {
alert ("Welcome");
} else i f(inputText == "bye") {
alert("See you later");
}
}