JAVASCRIPT

Get and Set Form Input Field Values

Learn how to programmatically retrieve and set the value of HTML input, textarea, and select elements, essential for form manipulation.

// Function to get the value of an input field
function getInputValue(elementId) {
  const inputField = document.getElementById(elementId);
  if (inputField) {
    return inputField.value;
  }
  console.error(`Input field with ID '${elementId}' not found.`);
  return null;
}

// Function to set the value of an input field
function setInputValue(elementId, newValue) {
  const inputField = document.getElementById(elementId);
  if (inputField) {
    inputField.value = newValue;
    console.log(`Input field '${elementId}' value set to '${newValue}'.`);
  } else {
    console.error(`Input field with ID '${elementId}' not found.`);
  }
}

// Example Usage:
// HTML: <input type="text" id="usernameInput" value="guest">
// console.log(getInputValue('usernameInput')); // "guest"
// setInputValue('usernameInput', 'admin'); // Sets value to "admin"
How it works: This snippet provides two utility functions: one to retrieve the current value of an HTML input (or textarea, select) element, and another to programmatically set its value. These are fundamental operations for handling user input in web forms, enabling dynamic pre-filling or extraction of form data for submission or client-side validation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs