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

รับค่าตัวเลขจาก User Input แสดงใน Console

ใช้ document.querySelector ดึงค่า Input แปลงเป็น Number ด้วย parseInt หรือ Number()

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Number Input</title>
</head>
<body>
  <div class="container">
    <p><strong>Example:</strong> Choose 1-100</p>
    <form>
      <div class="form-group">
        <label for="number">Give a number:</label>
        <input id="inputNumber" type="text" name="number" />
      </div>
    </form>
    <p id="output"></p>
  </div>
  <button class="btn" id="choose">Click Me</button>
  <script>
    function example() {
      let btn = document.querySelector("#choose");
      let randomNumber = Math.ceil(Math.random() * 100);
      btn.onclick = function() {
        let givenNumber = document.querySelector("#inputNumber").value;
        let valueInt = parseInt(givenNumber, 10); // Radix 10
        console.log("Random:", randomNumber, "Input:", valueInt);
        document.getElementById("output").textContent = 
          "Random: " + randomNumber + ", Your: " + valueInt;
      };
    }
    example();
  </script>
</body>
</html>

คำอธิบาย

  • input.value คืน String เสมอ
  • parseInt(str, 10) แปลง String → Integer (Radix 10 = ทศนิยม)
  • Number(str) แปลงเป็น Number (Float ได้)
  • Math.random() * 100 สุ่ม 0-99.999 → Math.ceil → 1-100
  • ควร Validate: isNaN(valueInt) ตรวจก่อนใช้

ผลลัพธ์

กรอกตัวเลข กด Click Me → Console แสดง Random และ Input | หน้าจอแสดงผลลัพธ์