JAVASCRIPT
Accessing and Modifying Form Input Values in JavaScript
Master how to programmatically get values from various form input types like text, checkbox, and select, and dynamically update them using JavaScript.
// HTML Example:
// <input type="text" id="usernameInput" value="guest">
// <input type="checkbox" id="newsletterCheckbox" checked>
// <select id="countrySelect">
// <option value="usa">USA</option>
// <option value="can" selected>Canada</option>
// <option value="mex">Mexico</option>
// </select>
// Get text input value
const usernameInput = document.getElementById('usernameInput');
console.log('Initial username:', usernameInput.value); // Output: Initial username: guest
usernameInput.value = 'john.doe';
console.log('Updated username:', usernameInput.value); // Output: Updated username: john.doe
// Get checkbox checked status
const newsletterCheckbox = document.getElementById('newsletterCheckbox');
console.log('Newsletter checked:', newsletterCheckbox.checked); // Output: Newsletter checked: true
newsletterCheckbox.checked = false;
console.log('Newsletter checked (updated):', newsletterCheckbox.checked); // Output: Newsletter checked (updated): false
// Get select dropdown value
const countrySelect = document.getElementById('countrySelect');
console.log('Selected country:', countrySelect.value); // Output: Selected country: can
countrySelect.value = 'mex';
console.log('Updated selected country:', countrySelect.value); // Output: Updated selected country: mex
// Handle radio buttons (requires iterating or using a common name)
// HTML Example:
// <input type="radio" name="paymentMethod" value="credit" id="creditRadio" checked>
// <input type="radio" name="paymentMethod" value="paypal" id="paypalRadio">
const selectedPaymentMethod = document.querySelector('input[name="paymentMethod"]:checked');
if (selectedPaymentMethod) {
console.log('Selected payment method:', selectedPaymentMethod.value); // Output: Selected payment method: credit
}
// Set a radio button as checked
const paypalRadio = document.getElementById('paypalRadio');
paypalRadio.checked = true;
const newlySelectedPaymentMethod = document.querySelector('input[name="paymentMethod"]:checked');
if (newlySelectedPaymentMethod) {
console.log('New selected payment method:', newlySelectedPaymentMethod.value); // Output: New selected payment method: paypal
}
How it works: Interacting with form elements is a fundamental aspect of web development. This snippet demonstrates how to programmatically access and modify the values of common form inputs. For text fields and select dropdowns, the `.value` property is used. For checkboxes and radio buttons, the `.checked` boolean property controls their state. For radio buttons, you often need to use `querySelector` with a CSS selector to find the currently checked option within a group identified by their `name` attribute.