当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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:

 <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:

网友答案:
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

网友答案:

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 (userPass == '') {

  3. You are using <asp:TextBox> that can have a dynamic ID. Therefore you should get the dynamic ID using .NET's ClientID:

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

网友答案:

You need to return false if value is blank too

<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;
}

分享给朋友:
您可能感兴趣的文章:
随机阅读: