Read and Update Values of Form Input Elements
Owner: SnippetBot
Created: 2026-08-31 00:00:29
Size: 2.12 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Get references to form elements
const myTextInput = document.getElementById('myText');
const mySelectInput = document.getElementById('mySelect');
const myCheckboxInput = document.getElementById('myCheckbox');
const submitButton = document.getElementById('submitForm');
const outputDiv = document.getElementById('output');
if (myTextInput && mySelectInput && myCheckboxInput && submitButton && outputDiv) {
// Read initial values
console.log('Initial Text:', myTextInput.value);
console.log('Initial Select:', mySelectInput.value);
console.log('Initial Checkbox:', myCheckboxInput.checked);
// Update values programmatically
myTextInput.value = 'Hello from JS!';
mySelectInput.value = 'option2'; // Set by option value
myCheckboxInput.checked = true;
// Attach an event listener to the submit button (or form itself)
submitButton.addEventListener('click', (event) => {
event.preventDefault(); // Prevent default form submission for demonstration
const currentText = myTextInput.value;
const currentSelect = mySelectInput.value;
const currentCheckbox = myCheckboxInput.checked;
const results = `Text Input: "${currentText}"
` +
`Select Input: "${currentSelect}"
` +
`Checkbox Checked: ${currentCheckbox}`;
outputDiv.textContent = results;
console.log('Current Form Values:
', results);
});
console.log('Form interaction example ready.');
} else {
console.error('One or more form elements not found.');
}
/*
HTML structure for testing:
<form id="myForm">
<label for="myText">Text Input:</label>
<input type="text" id="myText" value="Default Text"><br><br>
<label for="mySelect">Select Option:</label>
<select id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select><br><br>
<label for="myCheckbox">Check Me:</label>
<input type="checkbox" id="myCheckbox"><br><br>
<button type="submit" id="submitForm">Get Values</button>
</form>
<pre id="output"></pre>
*/