JAVASCRIPT
Reading and Setting Values of Form Inputs
Learn how to programmatically get and set the values of HTML form input fields, textareas, and select elements using JavaScript for robust client-side form handling and validation.
function handleFormInputs() {
// Get input values
const textInput = document.getElementById('myTextInput');
const passwordInput = document.getElementById('myPasswordInput');
const textareaInput = document.getElementById('myTextarea');
const selectElement = document.getElementById('mySelect');
const checkboxInput = document.getElementById('myCheckbox');
const textValue = textInput ? textInput.value : '';
const passwordValue = passwordInput ? passwordInput.value : '';
const textareaValue = textareaInput ? textareaInput.value : '';
const selectValue = selectElement ? selectElement.value : '';
const isChecked = checkboxInput ? checkboxInput.checked : false;
console.log('Text Input:', textValue);
console.log('Password Input:', passwordValue);
console.log('Textarea:', textareaValue);
console.log('Select:', selectValue);
console.log('Checkbox Checked:', isChecked);
// Set input values dynamically
if (textInput) textInput.value = 'New Value Set Programmatically';
if (textareaInput) textareaInput.value = 'This is updated content for the textarea.';
if (selectElement) selectElement.value = 'option2'; // Set by value attribute
if (checkboxInput) checkboxInput.checked = true; // Programmatically check it
console.log('--- Values updated ---');
console.log('Updated Text Input:', textInput ? textInput.value : '');
}
// Example HTML for context:
/*
<input type="text" id="myTextInput" value="Initial Text">
<input type="password" id="myPasswordInput" value="secret123">
<textarea id="myTextarea">Initial textarea content</textarea>
<select id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<input type="checkbox" id="myCheckbox" checked>
<button onclick="handleFormInputs()">Process Form</button>
*/
// Call it on page load or a button click
// handleFormInputs(); // Uncomment to run on load
How it works: This snippet provides a comprehensive guide to reading and setting values for various HTML form input elements using JavaScript. It demonstrates how to access the `value` property for text inputs, passwords, textareas, and select elements, and the `checked` property for checkboxes. This is fundamental for client-side form validation, dynamically pre-filling forms, or capturing user input before submission, offering robust control over form interactions.