[英]JQuery Validation With Multiple Sets Of Radio Buttons
我有一個form
,確實提交了8個radio
按鈕中的1個到php
$_POST
超級全局數組。 因此,我需要一些驗證。 提供此代碼的效果很好,對我有所幫助:
$("#form").submit(function (event) {
if(!$(":radio:checked").length) {
alert("You must select at least one emotional state!");
event.preventDefault();
}
});
但是,現在我被要求擁有2組8個radio
按鈕,其中用戶選擇2個答案,而不是最初的1個答案。 我需要代碼來確定在提交表單之前,已經從每8個按鈕集中選擇了至少一個radio
按鈕。 目前,代碼將檢查是否已選擇任何radio
按鈕,然后只要選擇了1個按鈕,該功能就會滿足,並跳至下一頁,這不是我想要的。
編輯
按鈕代碼:
<p><input type="radio" value="happy" name="perceived_emotion">Happy
<input type="radio" value="excited" name="perceived_emotion">Excited
<input type="radio" value="angry" name="perceived_emotion">Angry
<input type="radio" value="frustrated" name="perceived_emotion">Frustrated
<input type="radio" value="miserable" name="perceived_emotion">Miserable
<input type="radio" value="sad" name="perceived_emotion">Sad
<input type="radio" value="tired" name="perceived_emotion">Tired
<input type="radio" value="relaxed" name="perceived_emotion">Relaxed</p>
<p><input type="radio" value="happy" name="induced_emotion">Happy
<input type="radio" value="excited" name="induced_emotion">Excited
<input type="radio" value="angry" name="induced_emotion">Angry
<input type="radio" value="frustrated" name="induced_emotion">Frustrated
<input type="radio" value="miserable" name="induced_emotion">Miserable
<input type="radio" value="sad" name="induced_emotion">Sad
<input type="radio" value="tired" name="induced_emotion">Tired
<input type="radio" value="relaxed" name="induced_emotion">Relaxed</p>
這是form
代碼:
<form id="form" action="audio_handler.php?id=1" method="POST">
<div id="perceived_emotions">
<?php include("includes/induced_emotion_buttons.php"); ?>
</div>
<br />
<div id="induced_emotions">
<?php include("includes/perceived_emotion_buttons.php"); ?>
</div>
<p class="right"><input type="submit" name="submit" value="Submit"></p>
</form>
您要做的是將JQuery中的[name="value"]
選擇器與:checked
選擇器結合使用。 因此,您的新代碼將是:
if(!$('input[name="perceived_emotion"]:checked').length) {
alert("You must select at least one perceived emotional state!");
event.preventDefault();
return false;
}
if(!$('input[name="induced_emotion"]:checked').length) {
alert("You must select at least one induced emotional state!");
event.preventDefault();
return false;
}
所有這些都包裝在form事件中。
編輯:由於您只想一次顯示一個對話框,所以只需添加return false;
在每個if語句中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.