DIV CSS 佈局教程網

jQuery 操作 radio 單選按鈕的實作範例
編輯:JQuery特效代碼     

radio 單選鈕的讀取、設定與「同名但不同 type」的取捨,是表單開發的常見課題。本文用一個完整範例,示範如何取得選中的值、依條件設定選中,以及區分同名輸入框。

HTML 結構

注意範例中三個 radio 與一個 text 的 name 都是「study」:

<input name="study" type="radio" value="Jquery插件教程">Jquery插件教程
<input name="study" type="radio" value="Jquery學習">Jquery學習
<input name="study" type="radio" value="PHP學習">PHP學習
<input id="tijiao" type="button" value="確定">
<input id="set_jqeury_study" title="Jquery學習" type="button" value="將radio設定為Jquery學習">
<input name="study" type="text" value="請輸入您想學到的知識">
<input id="view_input_text" type="button" value="查看同名text值">

jQuery 邏輯

$(function(){
$('#tijiao').click(function(){
if ($("input:[name=study]:radio:checked").length == 0){
alert("請選擇您想學習的知識");
return false;
}
var study = $("input:[name=study]:radio:checked").val();
alert("謝謝!您選擇的是" + study);
})
$("#set_jqeury_study").click(function(){
var $button = $(this);
$("input:[name=study]:radio").each(function(){
if (this.value == $button.attr('title')){
this.checked = true;
}
})
})
$("#view_input_text").click(function(){
alert($("input[name=study]:text").val());
})
})

關鍵選擇器:$("input:[name=study]:radio:checked") 取得 name 為 study 且已選中的 radio,透過 length 是否為 0 判斷有沒有選;$("input[name=study]:text") 則精準抓到同名的 text 輸入框。加上 :radio 或 :text 就能區分同名但不同型別的元素。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved