สมมติว่าต่อไปนี้คือ input type checkbox ของเรา:
<label>John</label> <input id="checkedValue1" type="checkbox"> <label>David</label> <input id="checkedValue2" type="checkbox">
เราต้องการติ๊ก checkbox ใด checkbox หนึ่ง ใช้ property checked เพื่อติ๊ก checkbox
ตัวอย่าง
<!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>
<label>John</label>
<input id="checkedValue1" type="checkbox">
<label>David</label>
<input id="checkedValue2" type="checkbox">
</body>
<script>
document.querySelector('#checkedValue2').checked = true
</script>
</html>
เพื่อรันโปรแกรมข้างต้น ให้บันทึกไฟล์ชื่อ anyName.html (index.html) คลิกขวาที่ไฟล์และเลือก "Open with live server" ใน VS Code editor
ผลลัพธ์
ผลลัพธ์มีดังนี้:
