简体   繁体   English

无法使用Java脚本验证文本框

[英]not able to validate text box using java script

my input text box source like this: 我的输入文本框来源如下:

<asp:TextBox ID="TxtDepCode" runat="server" Height="18px"></asp:TextBox>

and my javascript function like this: 和我的JavaScript函数是这样的:

  <script type="text/javascript" language="javascript">
    function confirm_user() {
        var userPass = document.getElementById('TxtDepCode');
        alert(userPass)
        if (userPass=''){
        alert("value is blank")
        }
        if (confirm("Department already available, would you like to update ?") == true)
            return true;
        else
            return false;
    }
</script>

in submit button click i want to check wethar corresponding text is empty or not my submit button click event like this: 在提交按钮单击中,我要检查wethar对应的文本是否为空,或者我的提交按钮单击事件不是这样的:

var userPass = document.getElementById('TxtDepCode').value;

Or 要么

var userPass = document.getElementById('<%=TxtDepCode.ClientID%>').value;

Modify the first line of function to get value of textbox as above 修改函数的第一行以获取文本框的值,如上所述

if (userPass==''){

Modify if as above 修改if如上

The crucial issues in the code are as follows: 代码中的关键问题如下:

  1. Get the value of the password and not the element: 获取密码的值,而不是元素:

    var userPass = document.getElementById('TxtDepCode').value;

  2. Change the if to == or === instead of single = 将if更改为==或===而不是单个=

    if (userPass == '') {

  3. You are using <asp:TextBox> that can have a dynamic ID. 您正在使用可以具有动态ID的<asp:TextBox> Therefore you should get the dynamic ID using .NET's ClientID : 因此,您应该使用.NET的ClientID获得动态ID:

    var userPass = document.getElementById('<% =TxtDepCode.ClientID %>').value;

You need to return false if value is blank too 如果值也为空,则需要返回false

<script type="text/javascript" language="javascript">
function confirm_user() {
    var userPass = document.getElementById('TxtDepCode');
    alert(userPass)
    if (userPass.value == ''){ // == not = and userPass.value
    alert("value is blank");
    return false; // Need to stop the function
    }
    if (confirm("Department already available, would you like to update ?") == true)
        return true;
    else
        return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM