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

สร้างปุ่มเพิ่มข้อความใน HTML Input ด้วย JavaScript

ใช้ addEventListener('click') และ value += 'text' เพิ่มข้อความใน Input

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="clickButton">Click the button to add the input into the below Text Box</button>
    <br/><br />
    <input id="readTheInput" />

    <script>
        document.getElementById("clickButton").addEventListener("click", () => {
            document.getElementById("readTheInput").value += "JavaScript";
        });
    </script>
</body>
</html>

วิธีรันโปรแกรม

  1. บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
  2. คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor

ผลลัพธ์

กดปุ่มทุกครั้ง จะเพิ่มคำว่า "JavaScript" ต่อท้ายในช่อง Input