2015-01-04 49 views
0

我有這個網站jQuery的單選框檢查發現爲事先檢查項目

<div class="calsort btn-group" data-toggle="buttons"> 
    <label class="btn btn-primary "> 
     <input type="radio" name="options" id="rcal1" autocomplete="off" checked="checked">rcal1</label> 
    <label class="btn btn-primary"> 
     <input type="radio" name="options" id="rcal2" autocomplete="off">rcal2</label> 
    <label class="btn btn-primary"> 
     <input type="radio" name="options" id="rcal3" autocomplete="off">rcal3</label> 
</div> 

而且我的javascript

$(".calsort").click(function() { 

$(".calsort :checked").each(function() { 
rcal = this.id; 
    alert(rcal); 
}); 
}); 

所以,當我在測試JS撥弄這種功能,它的工作原理......但是,當我在其他js代碼的工作環境中測試,這是行不通的......但這個函數是單獨不涉及任何其他變量名稱或函數名稱。

我的問題是當我點擊rcal2按鈕時,它首先發出rcal1警報,當我點擊第二次時,它會發出警報rcal2.And同樣爲rcal3按鈕。第一次警告以前檢查過的值。

有沒有人告訴替代的方式來檢查哪些複選框被選中......我不想$(本)method..because其他功能也將使用這種循環方式。

回答

1

此當你點擊lable而不是radio button正在發生的事情。原因是當您點擊標籤時點擊事件發生時,先前選中的按鈕不會被清除。它甚至發生在jsfiddle(嘗試點擊標籤here)。

試試這個,

$(".calsort input").click(function() { 
 
    var rcal = this.id; 
 
    alert(rcal); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="calsort btn-group" data-toggle="buttons"> 
 
    <label class="btn btn-primary "> 
 
     <input type="radio" name="options" id="rcal1" autocomplete="off" checked="checked">rcal1</label> 
 
    <label class="btn btn-primary"> 
 
     <input type="radio" name="options" id="rcal2" autocomplete="off">rcal2</label> 
 
    <label class="btn btn-primary"> 
 
     <input type="radio" name="options" id="rcal3" autocomplete="off">rcal3</label> 
 
</div>

+0

哎啊好找:d非常感謝+1 – Vishnu

+0

哎我怎麼能在循環使用它? – Vishnu

+0

在什麼循環?任何示例代碼? –

0

這裏的另一種方式做,而不是.click()事件已經使用.change().change()事件的單選按鈕是獲取選定值的好方法。

JS:

working Demo

$(".calsort input").on('change', function() { 
    var self = jQuery(this); 
    var aResult = self.is(":checked"); 
    if (aResult) { 
     alert(self.attr('id')); 
    } 
});