2012-05-16 15 views
4

只是無法弄清楚......(並且從長時間的網絡搜索來看,我不是唯一一個。)我有jQT驗證,否則正常工作;只是不適用於無線電 - 我想要做的就是確認至少有一個按鈕已被點擊。我一直在試驗通過$ .tools.validator.fn設置自定義驗證函數,但是我找不到用於選擇器的正確的東西。我沒有看到源代碼的運氣。有什麼建議嗎?謝謝!如何讓jQuery Tools驗證工作在一組單選按鈕上?

+2

這個問題看起來類似:http://stackoverflow.com/questions/277589/validation-of-radio-button-group-using-jquery-validation-plugin。 –

回答

2

我不得不承認,這是一個黑客攻擊,需要根據您的需求進行調整。這是我想出來的,可能有更好的選擇。

樣品標記:

<form action="" id="theForm"> 
    <fieldset> 
    <input type="radio" name="sex" value="male" id="male" class="requiredCheckbox" /> <label for="male">Male</label><br /> 
    <input type="radio" name="sex" value="female" id="female" /> <label for="female">Female</label><br/> 
    <input type="radio" name="sex" value="unknown" id="unknown" /> <label for="unknown">Unknown</label> 
    </fieldset> 

    <input type="button" id="validate" value="Validate" /> 
</form> 
​ 

的Javascript自定義驗證方法和一個小兩輪牛車:

$.validator.addMethod('requiredCheckbox', function (val, elt) { 
    var valid = false; 

    $('input[name=' + $(elt).attr('name') + ']:radio').each(function(inx, elt) { 
     if (elt.checked === true) { 
      valid = true; 
      return; 
     } 
    }); 

    return valid; 
}, 'Select at least one checkbox'); 

var options = { 
    errorPlacement: function(error, elt) { 
     $(elt).before(error); 
    }, 
    errorElement: 'div' 
}; 
var validator = $('#theForm').validate(options); 

$('#validate').click(function() { 
    $('#theForm').valid(); 
});​ 

這裏的jsfiddle與工作示例:http://jsfiddle.net/9DRcz/

有趣的問題制定出雖然: - )

+0

一個好開始!有一個問題是,我正在尋找一種方法來讓jQuery Tools(非原始jQuery)中的驗證器正常工作,因爲我在代碼中的其他地方使用了該方法。但是我必須有單選按鈕驗證,所以我可能不得不把它吸收並切換到可用的代碼。我可能會回來更多的這個... –

2

我在哪裏(或結束):

  • 我放棄了試圖在jQuery工具中使用單選按鈕來驗證的東西。

  • @MK_Dev讓我瞭解了使用jQuery驗證插件(http://bassistance.de/jquery-plugins/jquery-plugin-validation/)的道路,非常感謝。然而,他的答案中的附加方法並不是必需的 - 我通過加載驗證插件獲得單選按鈕驗證,給單選按鈕之一一個「必需」類,並在窗體上調用.validate()。工作正常。

  • @ jason對Validation of radio button group using jQuery validation plugin的參考也付清了。我對這一切感到困惑的最後一點是,在該頁面上討論瞭如何不需要bassistance驗證插件 - jQuery(1.3.2 ??)可以單獨進行驗證。可能是,但我無法弄清楚。

無論如何,我現在有一些工作驗證,這比我今天早些時候說的更多。謝謝大家!

2

我得到它的工作。他們不會在jQueryTools Validator文檔中給出任何單選按鈕示例:http://jquerytools.org/documentation/validator/index.html

這裏是相關的源代碼。

在頁頭,包括:

<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script> 

<script> 
$(document).ready(function() { 
    $("#myform").validator(); 
}); 
</script>` 

在頁面正文:

<form id="myform" name="myform" method="post" action="next-page.php"> 
    <label>Option One</label> 
    <input type="radio" required="required" name="RadioGroup1" id="RadioButton_1" /> 
    <label>Option Two</label> 
    <input type="radio" required="required" name="RadioGroup1" id="RadioButton_2" /> 
    <label>Option Three</label> 
    <input type="radio" required="required" name="RadioGroup1" id="RadioButton_3" /> 

    <input type="submit" name="continue_to_next_page" id="submit" value="Continue" /> 
</form> 

讓我們知道,如果你的作品。