JAVASCRIPT
Manipulate Form Input Values and States with JavaScript
Master how to programmatically set and retrieve values for text inputs, checkboxes, radio buttons, and select elements using JavaScript DOM manipulation.
function manipulateFormInput(selector, value, type = 'text') {
const element = document.querySelector(selector);
if (!element) {
console.warn(`Element with selector '${selector}' not found.`);
return;
}
switch (type) {
case 'checkbox':
case 'radio':
element.checked = !!value; // Set checked state
console.log(`Input '${selector}' checked state: ${element.checked}`);
break;
case 'select':
element.value = value; // Set selected option by value
console.log(`Input '${selector}' selected value: ${element.value}`);
break;
case 'text': // Covers text, number, email, password, etc.
default:
element.value = value; // Set input text value
console.log(`Input '${selector}' value: ${element.value}`);
break;
}
}
// Example Usage:
// <input type="text" id="username">
// <input type="checkbox" id="newsletter">
// <select id="country"><option value="us">USA</option><option value="ca">Canada</option></select>
// manipulateFormInput('#username', 'john.doe');
// manipulateFormInput('#newsletter', true, 'checkbox');
// manipulateFormInput('#country', 'ca', 'select');
// To get values:
// const usernameVal = document.getElementById('username').value;
// const newsletterChecked = document.getElementById('newsletter').checked;
// const countryVal = document.getElementById('country').value;
How it works: This snippet provides a unified function to interact with various form input types. For text-based inputs (`text`, `number`, `email`), `element.value` is used to set or retrieve its content. For checkboxes and radio buttons, the `element.checked` boolean property controls their state. For `<select>` elements, `element.value` sets the selected option based on its `value` attribute.