radio是form表單中非常常用的一種表單元素,對於radio的操作中,都是利用radio的checked屬性,都是對radio的checked屬性做操作。擷取radio的選中值時,遍曆radio按鈕項,找到被選中(checked)的狀態的那個按鈕,然後返回其值;給radio賦值時,找到對應的按鈕項,將其checked屬性置為true即可。
擷取radio值
Method1 遍曆radio集合
假如我們給定頁面
<body> <p> <label for="DoorCt">Doors: <input type="radio" name="DoorCt" value="twoDoor" checked=”true”onclick="getValue()">Two <input type="radio" name="DoorCt" value="fourDoor" onclick="getValue()">Four </label> </p></body>
要擷取其中的選中的按鈕值,該怎麼取呢。
1 按照name屬性擷取該radio的集合
2 遍曆集合中的每一項元素
3 擷取元素的checked屬性,是否為true,為true,返回其value值
function getValue(){ // method 1 var radio = document.getElementsByName("DoorCt");for (i=0; i<radio.length; i++) {if (radio[i].checked) {alert(radio[i].value)}}}
這裡使用alert(radio[i].value)是為了直觀的效果,可以使用return radio[i].value 來返回value值。
細看一下getValue方法的實現。
var document.getElementsByName("DoorCt");
根據name屬性,擷取radio的集合,getElementsByName方法是document擷取對象的三個方法之一,擷取到的是集合。
緊接著 for (i=0;i<radio.length; i++) { 對集合中的元素開始遍曆
if (radio[i].checked) { 遍曆每一個元素時,檢查一下元素的checked屬性,是否為true,為true的,則是被選中的,將其值radio[i].value 值返回。
Method2 傳遞當前radio對象值
如果選項按鈕僅是根據其值做一些頁面選擇切換的話,還可以更方便一些。
給每個單選項綁定一個onclick方法,給方法傳值this。
<body><p><label for="DoorCt">Doors: <input type="radio" name="DoorCt" value="twoDoor" onclick="getValue(this)">Two<input type="radio" name="DoorCt" value="fourDoor" onclick="getValue(this)">Four</label></p></body>
this代表的是當前對象,即當前的<input > 輸入按鈕
傳到方法中之後
function getValue(obj) { // method 2 var value = obj.value;alert(value);}
直接擷取value屬性就可以了。
看到這裡,可不可以直接給getValue方法傳遞選中的value值呢,當然可以,直接傳遞value值,一步到位。
<body><p><label for="DoorCt">Doors: <input type="radio" name="DoorCt" value="twoDoor" onclick="getValue(this.value)">Two<input type="radio" name="DoorCt" value="fourDoor" onclick="getValue(this.value)">Four</label></p></body><script>function getValue(value){ // method2_1alert(value);}</script>
給radio賦值
給radio按鈕賦值跟取值差不多,都是利用radio的checked屬性,將要賦值的按鈕項的checked項置為true即可。
<body><p><label for="DoorCt">Doors: <input type="radio" name="DoorCt" value="twoDoor" onclick="getValue(this)">Two<input type="radio" name="DoorCt" value="fourDoor" onclick="getValue(this)">Four</label></p></body><script>function getValue(obj){ // method 2 var value = obj.value;alert(value);}window.onload = function(){var radio = document.getElementsByName("DoorCt");radio[0].checked = true;}
這裡待頁面載入完成後,執行window.onload事件,事件中選中選項按鈕的第一項,將其checked值置為true,即預設選中了第一項。