JAVASCRIPT
Read and Update Values of Form Input Elements
Learn to programmatically get the current value from various HTML form inputs (text, checkbox, select) and update them using JavaScript DOM manipulation for dynamic form control.
// Assume an HTML form with inputs:
// <input type="text" id="myTextInput" value="Initial Text">
// <input type="checkbox" id="myCheckbox" checked>
// <select id="mySelect">
// <option value="apple">Apple</option>
// <option value="banana" selected>Banana</option>
// <option value="orange">Orange</option>
// </select>
// Get input elements by their ID
const textInput = document.getElementById('myTextInput');
const checkboxInput = document.getElementById('myCheckbox');
const selectElement = document.getElementById('mySelect');
if (textInput) {
// 1. Get value from a text input
console.log('Text Input Value:', textInput.value);
// 2. Set value for a text input
textInput.value = 'New Value Programmatically Set';
console.log('Updated Text Input Value:', textInput.value);
}
if (checkboxInput) {
// 3. Get checked state from a checkbox
console.log('Checkbox Checked State:', checkboxInput.checked);
// 4. Set checked state for a checkbox
checkboxInput.checked = false; // Uncheck it
console.log('Updated Checkbox Checked State:', checkboxInput.checked);
}
if (selectElement) {
// 5. Get selected value from a select dropdown
console.log('Select Value:', selectElement.value);
// To get the displayed text of the selected option:
const selectedOptionText = selectElement.options[selectElement.selectedIndex].text;
console.log('Selected Option Text:', selectedOptionText);
// 6. Set selected value for a select dropdown
selectElement.value = 'orange'; // Selects the option with value 'orange'
console.log('Updated Select Value:', selectElement.value);
}
How it works: This snippet demonstrates how to interact with common HTML form input elements using JavaScript. For text inputs, `element.value` is used to both retrieve and set the input's current text. For checkboxes, `element.checked` provides or controls its boolean checked state. For dropdowns (`<select>`), `element.value` gets/sets the `value` attribute of the selected option, while `element.options[element.selectedIndex].text` can be used to retrieve the visible text of the currently selected option. These methods are fundamental for form validation, dynamic updates, and data submission.