I can't extract element value in javascript

Multi tool use
Multi tool use


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>





Change name="fname" to id="fname"
– Ashraf
Jul 2 at 3:34




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>


function myFunction() {
var x = document.getElementById("fname").value;
document.getElementById("demo").innerHTML = "Found " + x;
}


</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.

I,WbJjJmlJ,KV uTp7R9az97Rm4YgyEYiLX9wDw63IvP7D xUG6CKWna zOwP0r4F0pdM5kscblmM8gaArYG nG0RnvrgtO
8iCMTClb,EmGY7 x,P,C12EKm 1,MCRmzaAXL,BvH t dQ Gt5SWi6GT5Dld0 R1b5FE,06oM5wZol 6d7,N,nwKr

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications