使用多组单选按钮进行JQuery验证

时间:2014-11-24 21:50:21

标签: php jquery html forms

我有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>

1 个答案:

答案 0 :(得分:1)

您要做的是将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;
}

所有这些都包含在表单事件中。

编辑:由于您只想一次显示一个对话框,只需在每个if语句中添加return false;