[英]Validate radio buttons with jQuery on submit
我想使用jQuery驗證我的表單。 它具有單選按鈕組。
對於單個單選按鈕或解決方案組,我發現了多種解決方案,您必須在其中特別說明存在哪些組名。
就像這里: 用jquery驗證單選按鈕?
問題在於,該表單是在運行時生成的。 問題將保存在txt文件中(不要問,這是學校的練習)。 生成的HTML代碼如下所示:
<p>What's your gender?
<input type="radio" name="gender" value="m" />Male
<input type="radio" name="gender" value="f" />Female
</p>
<p>
How satisfied are you with out support?
<input type="radio" name="satisfaction" value="0%" />Not at all
<input type="radio" name="satisfaction" value="25%" />Not very much
<input type="radio" name="satisfaction" value="75%" />It was ok
<input type="radio" name="satisfaction" value="100% />It was very satisfying
</p>
該js文件是使用Twig生成的,因此可以遍歷所有單選按鈕組,但我想避免這種情況。
您需要先添加所有組(頁面加載會很好,但要確保組數組在全局范圍內),然后在提交表單/單擊按鈕時分別驗證每個組
var groups = [];
$(function() {
$("input[type=radio][name]").each(function() {
// Add the unique group name to the array
groups[$(this).attr("name")] = true;
});
});
$("button").click(function() {
$.each(groups, function(i, o) {
// For each group, check at least one is checked
var isValid = $("input[name='"+i+"']:checked").length;
alert(i + ": " + isValid);
});
});
我像這樣工作
var groups = [];
$(function() {
$("input[type=radio][name]").each(function() {
// Add the unique group name to the array
if (groups[groups.length - 1] != $(this).attr("name")) groups.push($(this).attr("name"));
});
});
$('form').submit(function () {
var isValid = true;
$.each(groups, function(i, o) {
// For each group, check at least one is checked
if (isValid) isValid = $("input[name='"+o+"']:checked").length;
});
if (!isValid) return false;
return true;
});
感謝Blade0rz!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.