onClientClick无法使用JavaScript

时间:2013-01-08 12:32:41

标签: javascript asp.net

如果输入无效,我试图显示警告,但OnClientClick不起作用,这是我的代码:

function validation1() {

    if (document.getElementById('firstname').value == "" || document.getElementById('firstname').value == "First Name..." ){
    alert("Please Enter First Name");
    } 
    if(document.getElementById('lastname').value == "" || document.getElementById('lastname').value == "Last Name..."){
    alert("Please Enter Last Name");
    }
}


<asp:Button runat="server" ID="SearchButton" Text="Instant Search" OnClick="SearchButton_Click" OnClientClick="validation1" />

我的代码在母版页中,这可能是个问题吗?

尝试了许多不同的方法来使用OnClientClick调用函数但没有成功:

2 个答案:

答案 0 :(得分:3)

您在函数调用中缺少括号(括号),您可能还希望验证函数的结果确定是否应触发服务器端点击:

function validation1() {

if (document.getElementById('firstname').value == "" ||document.getElementById('firstname').value == "First Name..." ){
   alert("Please Enter First Name");
   return false;
} 

if(document.getElementById('lastname').value == "" || document.getElementById('lastname').value == "Last Name..."){
   alert("Please Enter Last Name");
   return false;
}

return true;
}

<asp:Button runat="server" ID="SearchButton" Text="Instant Search" OnClick="SearchButton_Click" OnClientClick="return validation1();" />

这里的主要区别在于,如果验证通过或未通过验证,客户端点击函数返回一个值,很容易错过:)。

答案 1 :(得分:0)

试试这个

    function validation1() {

    if (document.getElementById('firstname').value == "" || document.getElementById('firstname').value == "First Name..." ){
    alert("Please Enter First Name");
    return false;
    } 
    if(document.getElementById('lastname').value == "" || document.getElementById('lastname').value == "Last Name..."){
    alert("Please Enter Last Name");
    return false;
    }
}

这是aspx代码

<asp:Button runat="server" ID="SearchButton" Text="Instant Search" OnClick="SearchButton_Click" OnClientClick="return validation1();" />