Unit 7 ยท JavaScript

7.8.3Working with forms

HTML
<form id='regForm'>
  <input type='text' id='username' name='username'>
  <input type='checkbox' id='agree'>
  <select id='city'><option value='col'>Colombo</option><option value='neg'>Negombo</option></select>
  <input type='radio' name='gender' value='male'> Male
  <input type='radio' name='gender' value='female'> Female
  <button type='submit'>Send</button>
</form>
JavaScript
const name = document.getElementById('username').value;       // text value
const agreed = document.getElementById('agree').checked;      // true or false
const city = document.getElementById('city').value;           // selected option value
const gender = document.querySelector('input[name=gender]:checked')?.value; // selected radio

document.getElementById('username').value = '';               // set or clear
document.getElementById('regForm').reset();                   // clear whole form

// Reading all fields at once
const data = new FormData(document.getElementById('regForm'));
console.log(data.get('username'));
console.log(Object.fromEntries(data));                        // plain object

Input values are always strings; convert numbers with Number().