ทำการเลือกรายการของ select ด้วย Javascript

ตัว select ปกติแล้วเราไม่สามารถกำหนดค่าให้กับมันด้วย value เหมือน input อื่นๆได้ แต่เราสามารถทำการเลือกรายการภายใน select ได้ด้วย property selectIndex ของ select ได้ครับ

นอกจากนี้ property นี้ยังทำการรายงานรายการที่เลือก เป็นอันดับที่ ของ option ภายใน select ได้ด้วย

<select name="group" id="group">
<option value="0">Abum</option>
<option value="1">Game</option>
<option value="2">Horoscope</option>
</select>

function setSelect( id ){
  document.getElementById( 'group' ).selectedIndex = id; // เลือกรายการที่ id
  alert(document.getElementById( 'group' ).selectedIndex); // คืนค่าอันดับที่เลือก
  alert(document.getElementById( 'group' ).value); // คืนค่า value ที่เลือก
}

ผู้เขียน goragod โพสต์เมื่อ 08 ต.ค. 2551 เปิดดู 11,998 ป้ายกำกับ Javascript
^