如何使用JavaScript防止空白字段?

时间:2022-01-25 03:26:15

I am using this to check if fields are empty. The problem is, the error message is never thrown when a field is empty, it allows submission. Is it because I am trying to run onclick and onclientclick on the button? This is my syntax

HTML

我用它来检查字段是否为空。问题是,当字段为空时,永远不会抛出错误消息,它允许提交。是因为我试图在按钮上运行onclick和onclientclick吗?这是我的语法HTML

<asp:Button ID="main1212" runat="server" Text="Check If JS Works" 
OnClick="DoSomethingDoNothing_OnClick" OnClientClick="return ValidateData();" />


JS

<script type="text/javascript">
function ValidateData() {
    var main1212, dropdownselection, dropdownselection1, field21
    main1212 = document.getElementByID("txt313").value;
    dropdownselection = document.getElementByID("dropdownlist1").value;
    dropdownselection1 = document.getElementByID("dropdownlist11").value;
    field21 = document.getElementByID("txt12").value; 
    if (main1212 == '')
    {
        alert("Error");
        return false;
    }
    if (dropdownselection == '')
    {
        alert("Error");
        return false;
    }
    if (dropdownlist1 == '')
    {
        alert("Error")
        return false;
    }
    if (field21 == '')
    {
        alert("Error");
        return false;
    }}
</script>



EDIT If I open the browser console and press the button that should run my script their are no errors displayed?

编辑如果我打开浏览器控制台并按下应该运行我的脚本的按钮,它们没有显示错误?

1 个解决方案

#1


0  

It's missing a semi-colon in this line (not sure) of the function ValidateData:

它在函数ValidateData的这一行(不确定)中缺少一个分号:

var main1212,dropdownselection,dropdownselection1,field21;

(it's good to avoid extra spaces and also not create variables for this)

(最好避免额外的空格,也不要为此创建变量)

And it could be more simple, or like this:

它可能更简单,或者像这样:

window.onload=function(){document.getElementById('main1212').onclick=function(){ValidateData();};}

#1


0  

It's missing a semi-colon in this line (not sure) of the function ValidateData:

它在函数ValidateData的这一行(不确定)中缺少一个分号:

var main1212,dropdownselection,dropdownselection1,field21;

(it's good to avoid extra spaces and also not create variables for this)

(最好避免额外的空格,也不要为此创建变量)

And it could be more simple, or like this:

它可能更简单,或者像这样:

window.onload=function(){document.getElementById('main1212').onclick=function(){ValidateData();};}