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

HTML DOM Input Button name Property - คุณสมบัติ name ของปุ่ม

คุณสมบัติ name ของ HTMLButtonElement หรือ HTMLInputElement (type=button/submit/reset) ใช้ **อ่านหรือเปลี่ยนค่า** ของแอตทริบิวต์ name ซึ่งใช้ระบุชื่อของปุ่มเมื่อส่งฟอร์ม

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

// อ่านค่า
const buttonName = buttonElement.name;

// ตั้งค่า
buttonElement.name = "newName";

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

<!DOCTYPE html>
<html>
<head>
  <title>HTML DOM name Property</title>
  <style>
    body { text-align: center; font-family: sans-serif; padding: 2rem; }
    .btn { 
      display: block; 
      margin: 1rem auto; 
      background: #db133a; 
      color: #fff; 
      border: 1px solid #db133a; 
      padding: 0.75rem 2rem; 
      border-radius: 50px; 
      width: 80%; 
      max-width: 300px;
      font-size: 1rem;
      cursor: pointer;
    }
    .show-name { 
      font-weight: bold; 
      font-size: 1.2rem; 
      color: #ffc107; 
      margin: 1rem 0;
    }
  </style>
</head>
<body>
  <h1>name Property Example</h1>
  
  <input type="submit" 
         class="btn" 
         value="คลิกเพื่อเปลี่ยน Name attribute" 
         name="Red_Button"
         onclick="changeName()">
  
  <div class="show-name" id="display"></div>
  
  <script>
    function changeName() {
      const btn = document.querySelector('.btn');
      const display = document.getElementById('display');
      
      // แสดงค่าเดิม
      display.textContent = 'ค่า name เดิม: ' + btn.name;
      
      // เปลี่ยนค่า
      btn.name = 'Round_Red_Button';
      
      // แสดงค่าใหม่หลัง 1 วินาที
      setTimeout(() => {
        display.textContent = 'ค่า name ใหม่: ' + btn.name;
      }, 1000);
    }
  </script>
</body>
</html>

ความสำคัญของ name attribute

  • Form submission: name ใช้เป็น key ใน form data ที่ส่งไป server (name=value)
  • Radio buttons: name เดียวกัน = กลุ่มเดียว (เลือกได้อย่างใดอย่างหนึ่ง)
  • JavaScript access: form.elements['name'] หรือ document.querySelector('[name="..."]')
  • Server-side: PHP $_POST['name'], Node.js req.body.name

name vs id

คุณสมบัติ name id
วัตถุประสงค์ ส่งข้อมูลฟอร์ม, จับกลุ่ม radio ระบุตัวตนเฉพาะ (unique) ใน DOM
ความซ้ำได้ ซ้ำได้ (radio group) ต้องไม่ซ้ำในหน้าเดียว
CSS selector [name="x"] #x
JavaScript form.elements.name document.getElementById()

ประเภทปุ่ม (type) และ name

<!-- Submit button - ส่งฟอร์ม พร้อม name/value -->
<input type="submit" name="action" value="save">  // ส่ง action=save

<!-- Button - ไม่ส่งฟอร์มอัตโนมัติ ใช้กับ JS -->
<input type="button" name="btnAction" value="Click">

<!-- Reset button - รีเซ็ตฟอร์ม -->
<input type="reset" name="resetBtn" value="Clear">

<!-- button tag (แนะนำมากกว่า input) -->
<button type="submit" name="action" value="delete">ลบ</button>

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

  • หลายปุ่ม submit ในฟอร์มเดียว - ตรวจสอบว่าปุ่มไหนถูกกดจาก name/value
  • Dynamic forms - เพิ่ม/ลบ/เปลี่ยน name ตามเงื่อนไข
  • Testing/Automation - ใช้ name เป็น selector ใน Selenium, Cypress