验证多个复选框和内爆函数

时间:2014-03-09 07:15:14

标签: javascript php mysql forms validation

以下是一个片段

<tr>
    <td>7</td>
    <td>Tick the Teaching Methods Used </td>
    <td>
        <input type="checkbox" id="lectures" name="lectures" value="lectures">Lectures &nbsp;
        <input type="checkbox" id="study" name="study" value="study">Case Study &nbsp;
        <input type="checkbox" id="audvid" name="audvid" value="audvid">Audio|Video &nbsp;
        <input type="checkbox" id="interactive" name="interactive" value="interactive">Interactive Methods &nbsp;
        <input type="checkbox" id="discussion" name="discussion" value="discussion">Discussion &nbsp;
        <input type="checkbox" id="role" name="role" value="role">Role Play &nbsp;
        <input type="checkbox" id="quiz" name="quiz" value="quiz">Quiz
    </td>
</tr>

,验证码为

if ((document.form1.lectures.checked == false)
      && (document.form1.study.checked == false)
      && (document.form1.audvid.checked == false)
      && (document.form1.interactive.checked == false)
      && (document.form1.discussion.checked == false)
      && (document.form1.role.checked == false)
      && (document.form1.quiz.checked == false)) { 

    alert("Please check any one method"); 
    isValid = false;
}
return isValid;

如何仅将选中的值插入mysql数据库,内爆似乎没有帮助

修改:如果我对所有复选框内幕使用相同的“名称”,但在这种情况下,我无法验证

2 个答案:

答案 0 :(得分:0)

对所有复选框使用相同的名称。你说implode,这很好。至于验证,将其更改为使用ID:

else if ((document.getElementById("lectures").checked == false)
      && (document.getElementById("study").checked == false)
      && (document.getElementById("audvid").checked == false)
      && (document.getElementById("interactive").checked == false)
      && (document.getElementById("discussion").checked == false)
      && (document.getElementById("role").checked == false)
      && (document.getElementById("quiz").checked == false)) { 

    alert("Please check any one method"); 
    isValid = false;
}
return isValid;

答案 1 :(得分:0)

如果选中(选中)复选框,则仅将其置于POST中。

PHP:

$keys = explode(',','lectures,study,audvid'); //get all keys
$result = array();

foreach ($keys as $key) {
  if (isset($_POST[$key]) && $_POST[$key]) { //selected!
    $result[] = $key;
  }
}

print_r($result); //only selected checkeboxes are in result.