.value 不适用于表单 javascript

.value not working in for forms javascript

当我使用表单元素时,我收到一条错误消息,指出它无法将属性设置为 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;
}

这是为了评估,所以需要这样做,否则我会使用 document.getElementById().value

欢迎使用 Whosebug!

regForm 未定义;你需要先定义它。

提示:对不会改变的值使用 const,这是很好的做法!

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;
}

希望这对您有所帮助:)