เพื่อเลือกตัวเลือกใน dropdown ล่วงหน้าด้วย JavaScript ใช้พรอเพอร์ตี้ selectedIndex กำหนด index ของตัวเลือกที่ต้องการ (เริ่มจาก 0)
Dropdown สร้างด้วย <select> ใน HTML JavaScript ใช้ <script> โดย add_select_id คือ id ของ select, add_item_index คือ index ตัวเลข
ตัวอย่าง
<!DOCTYPE html> <html>
<head>
<title>HTML select tag</title>
</head>
<body>
<p> Select any one:</p>
<form>
<select id="dropdown" name="dropdown" class="form-control">
<option value="Android">Android</option>
<option value="CSS">CSS</option>
<option value="Python">Python</option>
</select>
</form>
<script>
document.getElementById("dropdown").selectedIndex = "1"; // เลือก CSS (index 1)
</script>
</body>
</html>
วิธีอื่นๆ ที่ยืดหยุ่นกว่า
// 1. กำหนดค่า value โดยตรง (แนะนำ)
document.getElementById("dropdown").value = "CSS";
// 2. ใช้ selected property ของ option element
document.getElementById("dropdown").options[1].selected = true;
// 3. jQuery
$('#dropdown').val('CSS');
เหตุผลที่ควรใช้ .value แทน selectedIndex
- อ่านง่ายกว่า (semantic)
- ไม่ต้องนับ index
- ทนทานต่อการเปลี่ยนแปลงลำดับ option