JAVASCRIPT
Retrieving and Setting Values of Form Input Elements
Efficiently get current values from various HTML form inputs like text fields, checkboxes, and select dropdowns, and programmatically set their values using JavaScript.
document.addEventListener('DOMContentLoaded', () => {
const textInput = document.getElementById('myTextInput');
const checkboxInput = document.getElementById('myCheckbox');
const selectInput = document.getElementById('mySelect');
const outputDisplay = document.getElementById('output');
// Set initial values programmatically
if (textInput) textInput.value = 'Initial Value';
if (checkboxInput) checkboxInput.checked = true;
if (selectInput) selectInput.value = 'optionB'; // Must match an option's value
// Retrieve values on button click
document.getElementById('getValuesBtn').addEventListener('click', () => {
const textVal = textInput ? textInput.value : 'N/A';
const checkboxVal = checkboxInput ? checkboxInput.checked : 'N/A';
const selectVal = selectInput ? selectInput.value : 'N/A';
if (outputDisplay) {
outputDisplay.innerHTML = `Text: ${textVal}<br>Checkbox: ${checkboxVal}<br>Select: ${selectVal}`;
}
console.log(`Text: ${textVal}, Checkbox: ${checkboxVal}, Select: ${selectVal}`);
});
});
/*
HTML structure for context:
<input type="text" id="myTextInput" value="Default">
<label><input type="checkbox" id="myCheckbox"> Check Me</label>
<select id="mySelect">
<option value="optionA">Option A</option>
<option value="optionB">Option B</option>
<option value="optionC">Option C</option>
</select>
<button id="getValuesBtn">Get Values</button>
<div id="output"></div>
*/
How it works: Interacting with form elements is fundamental in web development. This snippet demonstrates how to both retrieve and set values for common input types. For text-based inputs (`<input type="text">`, `<textarea>`), the `value` property is used. For checkboxes and radio buttons, the `checked` boolean property controls their state. For `<select>` elements, the `value` property corresponds to the `value` attribute of the selected `<option>`, allowing programmatic selection of an option.