I want get input from html file and use the value in my JavaScript function, but I don’t know what the problem is.
I cant access my input because when I run my code I get this:
hi hiii
let name = document.getElementById("fname").value
function ShowMessage() {
document.write(" hi " + fname + " how are you? ");
}
<!DOCTYPE html>
<html>
<body>
<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
</form>
<button onclick="ShowMessage()">click</button><br><br>
</body>
</html>
5
Answers
i add this part to my code:
Write your function like this.
Hope it will help you.
Here is how I would do it with a much cleaner solution. I would add a class the button ".btn", and create an empty paragraph with a class "contents":
document.write
– useElement.textContent
insteadon*
attribute handlers, useElement.addEventListener()
instead.trim()
and anif
statement<form>
– if you don’t need to submit the formyour function:
Change to:
This is typing mistake or you are referring to the wrong variable. Hope that helps.