JAVASCRIPT

Get and Set Form Input Values in JavaScript

Learn to efficiently read user input from form fields and programmatically update input values using vanilla JavaScript, crucial for robust form handling and validation.

// HTML structure:
// <input type="text" id="myTextInput" value="Initial Text">
// <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>
// <button id="readValues">Read Values</button>
// <button id="setValues">Set New Values</button>

const textInput = document.getElementById('myTextInput');
const textareaInput = document.getElementById('myTextarea');
const selectInput = document.getElementById('mySelect');
const readButton = document.getElementById('readValues');
const setButton = document.getElementById('setValues');

readButton.addEventListener('click', () => {
  console.log('Text Input Value:', textInput.value);
  console.log('Textarea Value:', textareaInput.value);
  console.log('Select Value:', selectInput.value);
});

setButton.addEventListener('click', () => {
  textInput.value = 'New Text Value';
  textareaInput.value = 'Updated Textarea Content';
  selectInput.value = 'option3'; // Set by option's value attribute
  console.log('Values have been updated programmatically.');
});
How it works: This snippet demonstrates how to interact with common HTML form elements to either retrieve their current values or set new ones programmatically. For `<input>` (text, number, etc.) and `<textarea>` elements, the `value` property directly accesses or modifies their content. For `<select>` elements, setting the `value` property to the `value` attribute of one of its `<option>` children will select that option. This is fundamental for form validation, data submission, and pre-filling forms.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs