2013-11-01 29 views
0

我有一個單選按鈕,並在表單提交我檢查它是否被選中,如果不顯示錯誤消息。當單擊單選按鈕時刪除錯誤消息。 但即使選中了單選按鈕,它仍會返回true並顯示錯誤。請幫忙。 我試過調試,但因爲它是jQuery控件進入jquery庫內部,很難調試。jquery單選按鈕選中仍顯示錯誤

這是我在做什麼

$('input:radio').on('click', function (e) { 
    $('#errgender').text("*"); 
}); 

$(':submit').on('click', function (e) { 
    var valid = false; 
    if (radio_not_selected) { 
     valid = true; 
     $('[name="gender"]').focus(); 
     $('#errgender').text("Please specify gender"); 
    } 

    if (valid) e.preventDefault(); 
}); 

function radio_not_selected() { 
    var radio = $("input[name='gender']:checked"); 
    if (radio.length <= 0) return true; 
    else return false; 
} 
+1

一點題外話,這聽起來像你真的應該使用一個複選框,而不是單選按鈕。另外,你不能用「else if」開始一個條件? – adeneo

+1

在那裏做什麼是'別的'? 'else if(radio_not_selected){' – PSL

+0

對不起,我有其他條件,我排除了 – user2769614

回答

2

變化:

if (radio_not_selected) { 

到:

if (radio_not_selected()) { 
+0

這工作。謝謝。但爲什麼它會有所不同,我有複選框的另一個功能,沒有(),它工作得很好。 – user2769614

+0

你的版本只是測試函數是否存在,它並不實際運行函數。這是基本的Javascript語法,類似於大多數編程語言:您必須在函數名稱後加'()'來調用它。 – Barmar

0

你不使用你的函數。更改此:

if (radio_not_selected) { 

到:

if (radio_not_selected()) {