I can't extract element value in javascript
I can't extract element value in javascript
I'm new to Javascript and trying to adapt a script I found online but I'm unable to extract the value entered in the first name text field. I don't understand what I'm getting wrong. Please can someone take a look at it please? Thank you.
function myFunction() {
var x = document.getElementById("fname").value;
document.getElementById("demo").innerHTML = "Found " + x;
}
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
<button onclick="myFunction()">Get it</button>
<p id="demo"></p>
1 Answer
1
You are using document.getElementById()
to get the value of your element.
document.getElementById()
It means your element must have the id
attribute. In your case, you only have the name
attribute for your element. So it should be done this way.
id
name
<!DOCTYPE html>
<html>
<body>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname" id="lname"><br>
<input type="submit" value="Submit">
</form>
<button onclick="myFunction()">Get it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("fname").value;
document.getElementById("demo").innerHTML = "Found " + x;
}
</script>
</body>
</html>
I added the id
attribute to your form elements.
id
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Change name="fname" to id="fname"
– Ashraf
Jul 2 at 3:34