JAVASCRIPT
Get and Set Values of Form Input Fields
Understand how to programmatically retrieve and update values of various HTML form input fields using JavaScript for dynamic forms and data management.
function getFormInputValue(inputElementId) {
const input = document.getElementById(inputElementId);
if (!input) {
console.error(`Input element with ID "${inputElementId}" not found.`);
return null;
}
if (input.type === 'checkbox') {
return input.checked;
} else if (input.type === 'radio') {
// For radio buttons, generally query for the checked one by name
// This function gets the value of a specific radio button if it's checked.
return input.checked ? input.value : null;
}
return input.value;
}
function setFormInputValue(inputElementId, value) {
const input = document.getElementById(inputElementId);
if (!input) {
console.error(`Input element with ID "${inputElementId}" not found.`);
return;
}
if (input.type === 'checkbox') {
input.checked = !!value;
} else if (input.type === 'radio') {
// Sets a specific radio button as checked if its value matches the provided value
if (input.value === value) {
input.checked = true;
}
} else {
input.value = value;
}
}
How it works: This snippet provides utility functions to programmatically retrieve and update values of various HTML form input fields. It correctly handles the `value` property for text-based inputs and select elements, and the `checked` property for checkboxes and radio buttons, enabling dynamic form interaction and data management.