JAVASCRIPT

Reading and Updating Form Input Values

Learn how to access and dynamically modify the values of various HTML form inputs like text fields, checkboxes, and select elements using JavaScript DOM APIs.

const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
const subscribeCheckbox = document.getElementById('subscribe');
const genderRadios = document.querySelectorAll('input[name="gender"]');
const countrySelect = document.getElementById('country');
const outputDiv = document.getElementById('output');
const submitBtn = document.getElementById('submitBtn');

if (nameInput && emailInput && subscribeCheckbox && genderRadios && countrySelect && outputDiv && submitBtn) {

  // --- Reading Values ---
  submitBtn.addEventListener('click', (e) => {
    e.preventDefault(); // Prevent form submission for this example

    const name = nameInput.value;
    const email = emailInput.value;
    const subscribed = subscribeCheckbox.checked; // For checkboxes
    const selectedGender = Array.from(genderRadios).find(radio => radio.checked)?.value; // For radio buttons
    const selectedCountry = countrySelect.value;

    let outputContent = `
          Name: ${name}

          Email: ${email}

          Subscribed: ${subscribed ? 'Yes' : 'No'}

          Gender: ${selectedGender || 'Not selected'}

          Country: ${selectedCountry}

        `;
    outputDiv.textContent = outputContent;
  });

  // --- Updating Values Programmatically ---
  // Set default values or update on the fly
  nameInput.value = 'John Doe';
  emailInput.value = '[email protected]';
  subscribeCheckbox.checked = true; // Check the checkbox

  // Select a specific radio button
  genderRadios.forEach(radio => {
    if (radio.value === 'male') {
      radio.checked = true;
    }
  });

  // Select an option in a dropdown
  countrySelect.value = 'USA'; // Set by option value

  // Listen for input changes
  nameInput.addEventListener('input', () => {
    console.log('Name changed to:', nameInput.value);
  });
  countrySelect.addEventListener('change', () => {
    console.log('Country changed to:', countrySelect.value);
  });
}

// Example of HTML structure:
/*
<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" value="" /><br /><br />

  <label for="email">Email:</label>
  <input type="email" id="email" value="" /><br /><br />

  <input type="checkbox" id="subscribe" />
  <label for="subscribe">Subscribe to newsletter</label><br /><br />

  <label>Gender:</label><br />
  <input type="radio" id="male" name="gender" value="male" />
  <label for="male">Male</label>
  <input type="radio" id="female" name="gender" value="female" />
  <label for="female">Female</label><br /><br />

  <label for="country">Country:</label>
  <select id="country">
    <option value="">--Please choose an option--</option>
    <option value="USA">United States</option>
    <option value="CAN">Canada</option>
  </select><br /><br />

  <button type="submit" id="submitBtn">Get Form Values</button>
</form>
<div id="output" style="white-space: pre-wrap; margin-top: 20px; border: 1px solid #ccc; padding: 10px;"></div>
*/
How it works: This comprehensive snippet illustrates how to effectively read and update values of various HTML form input elements using vanilla JavaScript. It covers `text` inputs, `checkboxes` (using `checked`), `radio` buttons (finding the `checked` one), and `select` dropdowns. The code demonstrates both retrieving current values on a button click and programmatically setting initial or updated values, alongside listening for `input` and `change` events for real-time interaction.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs