Skip to content
On this page

Operating Forms

Using JavaScript to operate forms is similar to manipulating the DOM, as forms are part of the DOM tree.

However, input fields, dropdowns, etc., can accept user input. Therefore, using JavaScript to manipulate forms allows us to obtain user input or set new content in an input field.

The main types of HTML form input controls include:

  • Textbox: <input type="text"> for text input.
  • Password box: <input type="password"> for password input.
  • Radio button: <input type="radio"> for single selection.
  • Checkbox: <input type="checkbox"> for multiple selections.
  • Dropdown: <select> for single selection.
  • Hidden input: <input type="hidden"> which is not visible to the user but is sent to the server upon form submission.

Getting Values

If we have a reference to an <input> node, we can directly call .value to obtain the corresponding user input:

javascript
// <input type="text" id="email">
let input = document.getElementById('email');
input.value; // 'User input value'

This method applies to text, password, hidden, and select types. For radio buttons and checkboxes, the .value property always returns the preset HTML value. Instead, use .checked to determine if the option is selected:

javascript
// <label><input type="radio" name="weekday" id="monday" value="1"> Monday</label>
// <label><input type="radio" name="weekday" id="tuesday" value="2"> Tuesday</label>
let mon = document.getElementById('monday');
let tue = document.getElementById('tuesday');
mon.value; // '1'
tue.value; // '2'
mon.checked; // true or false
tue.checked; // true or false

Setting Values

Setting values is similar to getting them. For text, password, hidden, and select types, set .value directly:

javascript
// <input type="text" id="email">
let input = document.getElementById('email');
input.value = 'test@example.com'; // Updated textbox content

For radio buttons and checkboxes, set .checked to true or false.

HTML5 Controls

HTML5 introduced many standard controls, including date, datetime, datetime-local, color, etc., all using the <input> tag:

html
<input type="date" value="2021-12-02">
html
<input type="datetime-local" value="2021-12-02T20:21:12">
html
<input type="color" value="#ff0000">

Browsers that do not support HTML5 will recognize these new controls as type="text". Supported browsers will provide formatted strings. For instance, the value of a type="date" input ensures a valid YYYY-MM-DD format or an empty string.

Submitting Forms

JavaScript can handle form submissions in two ways (AJAX will be covered in later chapters).

The first method is to submit a form using the <form> element's .submit() method, for example, responding to a button's click event:

html
<!-- HTML -->
<form id="test-form">
    <input type="text" name="test">
    <button type="button" onclick="doSubmitForm()">Submit</button>
</form>

<script>
function doSubmitForm() {
    let form = document.getElementById('test-form');
    // Modify form's input here...
    // Submit form:
    form.submit();
}
</script>

This method disrupts the browser's normal form submission. The browser typically submits the form when clicking a <button type="submit"> or pressing Enter in the last input field. The second method responds to the <form>'s onsubmit event, allowing modifications before submission:

html
<!-- HTML -->
<form id="test-form" onsubmit="return checkForm()">
    <input type="text" name="test">
    <button type="submit">Submit</button>
</form>

<script>
function checkForm() {
    let form = document.getElementById('test-form');
    // Modify form's input here...
    // Proceed:
    return true;
}
</script>

Note to return true to inform the browser to continue submission; if return false, the form will not submit, typically indicating user input errors.

While checking and modifying <input>, utilize <input type="hidden"> to pass data.

For instance, many login forms require a username and password, but for security reasons, plain text passwords should not be transmitted; instead, send the MD5 hash. A common practice is to modify the <input> directly:

html
<!-- HTML -->
<form id="login-form" method="post" onsubmit="return checkForm()">
    <input type="text" id="username" name="username">
    <input type="password" id="password" name="password">
    <button type="submit">Submit</button>
</form>

<script>
function checkForm() {
    let pwd = document.getElementById('password');
    // Convert user input plaintext to MD5:
    pwd.value = toMD5(pwd.value);
    // Proceed:
    return true;
}
</script>

This method seems fine, but when the user submits the password, the password field suddenly changes from asterisks to 32 characters (since MD5 has 32 characters).

To avoid altering user input visibility, use <input type="hidden">:

html
<!-- HTML -->
<form id="login-form" method="post" onsubmit="return checkForm()">
    <input type="text" id="username" name="username">
    <input type="password" id="input-password">
    <input type="hidden" id="md5-password" name="password">
    <button type="submit">Submit</button>
</form>

<script>
function checkForm() {
    let input_pwd = document.getElementById('input-password');
    let md5_pwd = document.getElementById('md5-password');
    // Convert user input plaintext to MD5:
    md5_pwd.value = toMD5(input_pwd.value);
    // Proceed:
    return true;
}
</script>

Note that the <input> with id="md5-password" has name="password", while the user input field id="input-password" does not have a name attribute. Inputs without a name will not be submitted.

Exercise

Use JavaScript to validate user registration information. If any of the following conditions are not met, display an error and prevent form submission:

  • Username must be 3-10 alphanumeric characters.
  • Password must be 6-20 characters.
  • Passwords must match.
html
<!-- HTML Structure -->
<form id="test-register" action="#" target="_blank" onsubmit="return checkRegisterForm()">
    <p id="test-error" style="color:red"></p>
    <p>
        Username: <input type="text" id="username" name="username">
    </p>
    <p>
        Password: <input type="password" id="password" name="password">
    </p>
    <p>
        Repeat Password: <input type="password" id="password-2">
    </p>
    <p>
        <button type="submit">Submit</button> <button type="reset">Reset</button>
    </p>
</form>

window.checkRegisterForm = function () {
    // TODO:
    return false;
};

// Test:
(function () {
    window.testFormHandler = window.checkRegisterForm;
    let form = document.getElementById('test-register');
    if (form.dispatchEvent) {
        let event = new Event('submit', {
            bubbles: true,
            cancelable: true
        });
        form.dispatchEvent(event);
    } else {
        form.fireEvent('onsubmit');
    }
})();
Operating Forms has loaded