Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Làm cho JavaScript nhận input HTML từ người dùng, parse và hiển thị

Giá trị input HTML là chuỗi. Để chuyển chuỗi thành số nguyên, dùng parseInt().

Ví dụ

Mã minh họa:

<!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> 
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> 
<script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 
<body> 
  <input type="text" id="txtInput" placeholder="Nhập một số"> 
  <button type="button" onclick="result();">Lấy số</button> 
</body> 
<script> 
  function result() { 
    var numberValue = document.getElementById("txtInput").value; 
    if (!isNaN(numberValue)) 
      console.log("Giá trị = " + parseInt(numberValue)); 
    else 
      console.log("Vui lòng nhập giá trị số nguyên..."); 
  } 
</script> 
</html>

Để chạy chương trình, lưu file index.html và mở với Live Server trong VSCode.

Kết quả

Khi nhập số và nhấn nút, console in số nguyên đã parse. Nếu nhập chữ, báo lỗi.