JAVASCRIPT
Get and Set Values of Form Input Elements
Learn to programmatically retrieve and update values of form input fields, textareas, and selects using JavaScript DOM manipulation.
function getInputValue(elementId) {
const inputElement = document.getElementById(elementId);
if (inputElement) {
// Works for input, textarea, and select elements
return inputElement.value;
} else {
console.warn(`Input element with ID "${elementId}" not found.`);
return null;
}
}
function setInputValue(elementId, value) {
const inputElement = document.getElementById(elementId);
if (inputElement) {
inputElement.value = value;
} else {
console.warn(`Input element with ID "${elementId}" not found.`);
}
}
// Usage example:
// HTML: <input type="text" id="usernameInput" value="initialName"><textarea id="commentBox"></textarea><select id="countrySelect"><option value="US">USA</option><option value="CA">Canada</option></select>
// console.log(getInputValue('usernameInput')); // Retrieves "initialName"
// setInputValue('usernameInput', 'JohnDoe'); // Updates the input field
// setInputValue('commentBox', 'Hello world!'); // Sets textarea content
// setInputValue('countrySelect', 'CA'); // Selects the 'Canada' option
How it works: These two functions provide simple utilities to interact with common form elements like text inputs, textareas, and select dropdowns. `getInputValue` retrieves the current value of a specified element, while `setInputValue` updates it. This is crucial for pre-populating forms, validating user input, or dynamically changing form data based on application logic without server interaction.