这可能是一个愚蠢的问题,但这是我第一年使用像javascript这样的东西。 我有一些警告框,我想知道是否有可能只显示一个警告框(在javascript中),包含我希望他们做的所有事情。 当他们填写其中一个输入或按钮时,指示者只会显示其他缺失的东西。
(我正在收到第一个代码的警告。当我填写它时,我会收到下一个代码的警报,依此类推。我想把所有代码放在一起。)
/*validate name*/
var n=document.forms["check"]["name"].value;
if(n==null||n=="")
{
alert("Please, fill in your name.");
return false;
}
/*validate the sex*/
if(document.getElementById('male').checked)
{
}
else if(document.getElementById('female').checked)
{
}
else
{
alert("Please, enter your gender.");
return false;
}
/*validate the E-mail*/
var e=document.forms["check"]["email"].value;
var atpos=e.indexOf("@");
var dotpos=e.lastIndexOf(".");
if(e==null||e=="")
{
alert("Please, fill in your e-mail.");
return false;
}
if(atpos<1 || dotpos<atpos+2 || dotpos+2>=e.length)
{
alert("This isn't a valid e-mail address.");
return false;
}
/*validate agreement*/
if(document.getElementById("I don't want my information to be part of this website.").checked)
{
}
else if(document.getElementById("I wish to be registered.").checked)
{
}
else if(document.getElementById("I wish to get the new content of this website.").checked)
{
}
else
{
alert("Please, tell us what we can do with your information.");
return false;
}
/*validate the terms*/
if(document.getElementById("yes").checked)
{
}
else if(document.getElementById("no").checked)
{
alert("You have to agree with the terms.");
return false;
}
else
{
alert("Please, enter the terms.");
return false;
}
答案 0 :(得分:1)
// initialise an array to populate along the way
var alerts = [];
/*validate name*/
var n = document.forms[ "check" ][ "name" ].value;
if ( n == null || n == "" ) {
// push message onto the array
alerts.push( "Please, fill in your name." );
return false;
}
/*validate the sex*/
if ( document.getElementById( 'male' ).checked ) {} else if ( document.getElementById( 'female' ).checked ) {} else {
// push message onto the array
alerts.push( "Please, enter your gender." );
return false;
}
/*validate the E-mail*/
var e = document.forms[ "check" ][ "email" ].value;
var atpos = e.indexOf( "@" );
var dotpos = e.lastIndexOf( "." );
if ( e == null || e == "" ) {
// push message onto the array
alerts.push( "Please, fill in your e-mail." );
return false;
}
if ( atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= e.length ) {
// push message onto the array
alerts.push( "This isn't a valid e-mail address." );
return false;
}
// join up the array of messages, and alert the user...
alert(alerts.join(", "));
// initialise an array to populate along the way
var alerts = [];
...
// push messages onto the array
// (repeat this step for all messages)
alerts.push( "Any validation message" );
...
// join up the array of messages, and alert the user...
alert(alerts.join(", "));