我有一张表格
<form method="post" action="sendmail.php" name="Email form">
Message ID
<input type="text" name="message_id" /><br/><br/>
Aggressive conduct
<input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct
<input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct
<input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct
<input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" />
</form>
我需要某种验证javascript:
有人可以帮忙吗?
答案 0 :(得分:0)
您必须在提交前进行验证。
在表单中添加一个on submit事件处理程序(将在提交表单时调用):
您可以通过两种方式执行此操作:
<form method="post" action="sendmail.php" name="Email form" onsubmit=validate()>
OR
<script>
部分中的:
window.onload = init;
function init()
{
document.forms["Email form"].onsubmit = function()
{
validate();
return false;
};
}
现在编写验证函数本身(上述两个选项都相同):
function validate()
{
var form = document.forms["Email form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") //No value in the "message_id" box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
答案 1 :(得分:0)
<强>更新即可。现在应该可以了。
// Register onsubmit callback function (this will be called when the user submit his data).
document.forms[0].onsubmit = validate;
function validate() {
var message = document.getElementsByTagName('input')[0].value,
radioButtons = document.getElementsByTagName('input'),
oneRadioChecked = false;
// check that message is not empty
if (message.length === 0) {
alert("no message inserted");
return false;
}
// check that at least one radio has been checked
for (var i = 0; i < radioButtons.length && !oneRadioChecked; i++) {
oneRadioChecked = (radioButtons[i].type === "radio" &&radioButtons[i].checked);
}
if (!oneRadioChecked) {
alert("no radio button checked");
return false;
}
}