JAVASCRIPT

Programmatically Set Input Values and Checkboxes

Learn to update the values of text inputs, select options, and the checked state of checkboxes/radio buttons directly via JavaScript.

function updateFormFields(formId) {
  const form = document.getElementById(formId);
  if (!form) {
    console.error('Form not found.');
    return;
  }

  // Get input elements by name within the form
  const nameInput = form.elements.name; // <input type="text" name="name">
  const emailInput = form.elements.email; // <input type="email" name="email">
  const countrySelect = form.elements.country; // <select name="country">
  const subscribeCheckbox = form.elements.subscribe; // <input type="checkbox" name="subscribe">
  const genderRadios = form.elements.gender; // <input type="radio" name="gender">

  // Update text input value
  if (nameInput) nameInput.value = 'John Doe';
  if (emailInput) emailInput.value = '[email protected]';

  // Update select element value
  // Ensure the option with this value exists
  if (countrySelect) countrySelect.value = 'USA';

  // Update checkbox checked state
  if (subscribeCheckbox) subscribeCheckbox.checked = true;

  // Update radio button checked state (by iterating or directly accessing value)
  if (genderRadios) {
    // Method 1: Set value directly on the group, if supported by browser (often works)
    // genderRadios.value = 'male';

    // Method 2: Iterate and check
    for (const radio of genderRadios) {
      if (radio.value === 'female') {
        radio.checked = true;
        break;
      }
    }
  }

  console.log('Form fields updated programmatically.');
}

// Example Usage:
// <form id="myForm">
//   <input type="text" name="name" value="">
//   <input type="email" name="email" value="">
//   <select name="country">
//     <option value="CAN">Canada</option>
//     <option value="USA">United States</option>
//   </select>
//   <input type="checkbox" name="subscribe"> Subscribe
//   <input type="radio" name="gender" value="male"> Male
//   <input type="radio" name="gender" value="female"> Female
// </form>
// updateFormFields('myForm');
How it works: This snippet demonstrates how to programmatically set the values and states of various form input elements. It shows how to update text inputs (`value` property), select dropdowns (`value` property by matching an option's value), and checkboxes (`checked` boolean property). For radio buttons, you can iterate through the group to find and check the desired option or sometimes set the `value` on the radio group directly if the browser supports it.

Need help integrating this into your project?

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

Hire DigitalCodeLabs