Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

HTML DOM Option defaultSelected Property - สถานะเลือกเริ่มต้น

คุณสมบัติ defaultSelected ของ HTMLOptionElement ใช้ **อ่านสถานะเริ่มต้น** ว่าตัวเลือกนี้ถูกเลือกไว้ตั้งแต่โหลดหน้า (มีแอตทริบิวต์ selected) หรือไม่ เป็น **read-only property**

ความแตกต่าง defaultSelected vs selected

คุณสมบัติ ประเภท คำอธิบาย
defaultSelected Read-only สถานะเริ่มต้น (มี selected attribute ตอนโหลด)
selected Read/Write สถานะปัจจุบัน (ผู้ใช้เลือก/เปลี่ยนไปแล้ว)

รูปแบบการใช้งาน

// อ่านค่าเท่านั้น
const wasInitiallySelected = optionElement.defaultSelected;
// true = มี selected attribute ตอนโหลดหน้า
// false = ไม่มี selected attribute ตอนโหลดหน้า

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; padding: 2rem; text-align: center; 
           background: linear-gradient(135deg, #FBAB7E 0%, #F7CE68 100%); 
           min-height: 100vh; color: #333; }
    h1 { color: #23CE6B; }
    .dropdown { 
      width: 35%; min-width: 250px; 
      padding: 10px; 
      font-size: 1rem; 
      border: 2px solid #fff; 
      border-radius: 8px;
      background: white;
    }
    .btn { 
      background: #0197F6; 
      color: white; 
      border: none; 
      padding: 12px 24px; 
      border-radius: 6px; 
      cursor: pointer; 
      font-weight: bold;
      margin-top: 1rem;
      display: block;
      margin-left: auto;
      margin-right: auto;
    }
    .show { font-size: 1.1rem; font-weight: bold; margin-top: 1rem; color: #23CE6B; }
    table { width: 100%; max-width: 500px; margin: 1rem auto; border-collapse: collapse; }
    th, td { padding: 8px; border: 1px solid #ddd; text-align: left; }
    th { background: #f5f5f5; }
    .selected { background: #e8f5e9; }
  </style>
</head>
<body>
  <h1>DOM Option defaultSelected Demo</h1>
  <p>เลือกวิชาที่คุณชอบ (Maths ถูกเลือกไว้ตั้งแต่โหลด):</p>
  
  <select class="dropdown" id="subjectSelect">
    <option value="phy">Physics</option>
    <option value="math" selected>Maths</option>
    <option value="chem">Chemistry</option>
    <option value="eng">English</option>
  </select>
  
  <button class="btn" onclick="showDefaultSelected()">ตรวจสอบ defaultSelected</button>
  <div class="show" id="result"></div>
  
  <table id="detailTable" style="display:none;">
    <thead>
      <tr><th>Index</th><th>Text</th><th>Value</th><th>defaultSelected</th><th>selected (current)</th></tr>
    </thead>
    <tbody></tbody>
  </table>
  
  <script>
    function showDefaultSelected() {
      const select = document.getElementById('subjectSelect');
      const options = select.options;
      const tbody = document.querySelector('#detailTable tbody');
      
      tbody.innerHTML = '';
      
      for (let i = 0; i < options.length; i++) {
        const opt = options[i];
        const row = document.createElement('tr');
        if (opt.defaultSelected) row.classList.add('selected');
        
        row.innerHTML = `
          ${i}
          ${opt.text}
          ${opt.value}
          ${opt.defaultSelected ? '✅ true' : '❌ false'}
          ${opt.selected ? '✅ true' : '❌ false'}
        `;
        tbody.appendChild(row);
      }
      
      document.getElementById('detailTable').style.display = 'table';
      
      // แสดงสรุป
      const initiallySelected = Array.from(options).find(opt => opt.defaultSelected);
      document.getElementById('result').innerHTML = 
        initiallySelected 
          ? `ค่าเริ่มต้นที่ถูกเลือก: ${initiallySelected.text} (value: ${initiallySelected.value})`
          : 'ไม่มีค่าเริ่มต้นที่เลือก';
    }
  </script>
</body>
</html>

การใช้งานจริง

  • **Reset form** - คืนค่า select ให้เป็นค่าเริ่มต้น: select.selectedIndex = Array.from(select.options).findIndex(o => o.defaultSelected)
  • **Track changes** - เปรียบเทียบ selected กับ defaultSelected เพื่อรู้ว่าผู้ใช้เปลี่ยนค่าหรือไม่
  • **Form dirty checking** - ตรวจสอบว่าฟอร์มมีการเปลี่ยนแปลงจากค่าเดิม

ตัวอย่าง: Reset Form ให้กลับค่าเริ่มต้น

<script>
  function resetSelectToDefault(selectElement) {
    const options = selectElement.options;
    for (let i = 0; i < options.length; i++) {
      if (options[i].defaultSelected) {
        selectElement.selectedIndex = i;
        break;
      }
    }
  }
  
  // หรือสำหรับ form ทั้งหมด
  function resetFormToDefault(form) {
    form.querySelectorAll('select').forEach(resetSelectToDefault);
    // input/textarea ใช้ defaultValue property
    form.querySelectorAll('input, textarea').forEach(el => {
      el.value = el.defaultValue;
    });
    // checkbox/radio ใช้ defaultChecked
    form.querySelectorAll('input[type="checkbox"], input[type="radio"]').forEach(el => {
      el.checked = el.defaultChecked;
    });
  }
</script>

defaultValue / defaultChecked สำหรับ input อื่นๆ

Element Default Property Current Property
<input type="text"> etc. defaultValue value
<textarea> defaultValue value
<input type="checkbox/radio"> defaultChecked checked
<option> defaultSelected selected