.value not working in for forms javascript


When I use the form element I get an error saying that it can’t set the properties to undefined.


<form name="regForm">
        <tr> <!-- First Name -->
                <input id="firstName" type="text" placeholder="First Name">
        <tr> <!-- Error Box -->
                <p id="returnOutput"></p>
        <tr> <!-- Submit button -->
                <button type="button" onclick="validateForm()">Sign Up</button>


function validateForm() {
    var firstName = regForm.firstName.value;
    regForm.returnOutput.value = firstName;

This is for an assessment so it needs to be done this way otherwise I would be using document.getElementById().value


Welcome to StackOverflow!

regForm is undefined; you need to define it first.

Just a tip: use const for values that won’t change, it’s good practise!

function validateForm() {
    // SELECT regForm by it's name. It doesn't have an ID, so we have to select it by name. However, if it did have an ID, we can use it. 0 is just to select the first element it finds since getElementsByName returns a node list
    const regForm = document.getElementsByName("regForm")[0]
    // Declare firstName as the firstname.value
    const firstName = regForm.firstName.value;
    // Finally, append it to body :)
    document.getElementById("returnOutput").innerHTML = firstName;

Hope this helped 🙂

Answered By – Joey M

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.