ใช้ localStorage.setItem("key", value) บันทึก และ localStorage.getItem("key") ดึงค่า
ตัวอย่างโค้ด
<!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>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<body>
<input type="text" id="txtName" placeholder="Enter some value..." />
</body>
<script>
var textBoxNameHTML = document.getElementById('txtName');
textBoxNameHTML.addEventListener('change', (e) => {
localStorage.setItem("textBoxValue", e.target.value);
});
</script>
</html>บันทึกเป็น index.html เปิดด้วย Live Server
ผลลัพธ์
พิมพ์ในช่อง input → กด Enter → ค่าถูกบันทึกใน localStorage
เปิด DevTools Console → พิมพ์ localStorage.getItem("textBoxValue") → ได้ค่าที่ป้อน




คำอธิบาย: localStorage เก็บข้อมูลแบบ key-value คงอยู่จนกว่าจะลบ ใช้ได้ข้าม session/tab เดียวกัน origin