Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript-在验证后防止页面重定向_Javascript_Html - Fatal编程技术网

Javascript-在验证后防止页面重定向

Javascript-在验证后防止页面重定向,javascript,html,Javascript,Html,我有一个下拉列表-如果用户试图提交页面,但没有从下拉列表中选择选项,那么我希望出现一个警告消息框,然后页面停留在原来的位置,而不是导航到另一个页面 当前,下拉列表出现,但页面仍重定向到另一个页面。我如何防止这种情况 我试过“return false”,但没用 函数validateDropDown(){ var e=document.getElementById(“颜色”); var strUser=e.options[e.selectedIndex].value var strColor1 =

我有一个下拉列表-如果用户试图提交页面,但没有从下拉列表中选择选项,那么我希望出现一个警告消息框,然后页面停留在原来的位置,而不是导航到另一个页面

当前,下拉列表出现,但页面仍重定向到另一个页面。我如何防止这种情况

我试过“return false”,但没用

函数validateDropDown(){

var e=document.getElementById(“颜色”); var strUser=e.options[e.selectedIndex].value

var strColor1 = e.options[e.selectedIndex].text;

var strColor = e.options[e.selectedIndex].text;
            if(strColor==0)
            {
                alert("Please select a color");
                return false;//This is what I tried to prevent page redirection, but it doesn't work.
            }
}

使用“防止默认值”:

function validateDropDown(event) {

var e = document.getElementById("services1"); var strUser = e.options[e.selectedIndex].value;

var strUser1 = e.options[e.selectedIndex].text;

var strUser1 = e.options[e.selectedIndex].text;
            if(strUser==0)
            {
                alert("Please select a service");
                event.preventDefault();
            }
}

您可以使用W3解释的
event.preventDefault()
,而不是在函数中返回
false
,它完全满足您的要求

函数validateDropDown(事件){//添加参数事件
var e=document.getElementById(“services1”);
var strUser=e.options[e.selectedIndex].value;
var strUser1=e.options[e.selectedIndex].text;
var strUser1=e.options[e.selectedIndex].text;
如果(strUser==0){
警报(“请选择一项服务”);
event.preventDefault();//添加阻止默认值
}

}
谢谢!我还在学习JS,所以我之前错过了。谢谢你的帮助@莫哈纳拉文德:没问题。快乐编码