Home > Software engineering >  .value not working in for forms javascript
.value not working in for forms javascript

Time:06-04

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

html:

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

Javascript:

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

CodePudding user response:

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 :)

  • Related