I have this blur function as shown below and on first time it dosen't check and when text changed for the second time it works
<script type = "text/javascript">
function ShowAvailability() {
var userName = $("#<%=txtUsername.ClientID %>");
$("#<%=txtUsername.ClientID %>").blur(function () {
userName = $(this).val();
if (userName.length < 5) {
$("#mesg")[0].innerHTML = "";
}
else {
$.ajax({
type: "POST",
url: "Default.aspx/CheckUserName",
data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response);
}
});
}
});
}
function OnSuccess(response) {
var mesg = $("#mesg")[0];
switch (response.d) {
case "true":
mesg.style.color = "green";
mesg.innerHTML = "Available";
break;
case "false":
mesg.style.color = "red";
mesg.innerHTML = "Not Available";
break;
case "error":
mesg.style.color = "red";
mesg.innerHTML = "Error occured";
break;
}
}
function OnChange(txt) {
$("#mesg")[0].innerHTML = "";
}
This is my textbox:
<asp:TextBox ID="txtUsername" runat="server" BorderStyle="Solid" BorderWidth="1px" BorderColor="#0099CC" BackColor="#FAFFBD" AutoCompleteType="Disabled" onkeyup = "OnChange(this)" Onblur="ShowAvailability()"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="txtUsername" ErrorMessage="User Name is required."
ToolTip="User Name is required."
CssClass="signupvalidators" ForeColor="Red">*</asp:RequiredFieldValidator>
<span id = "mesg"></span>
Here I'm checking it:
<System.Web.Services.WebMethod()> _
Public Shared Function CheckUserName(ByVal userName As String) As String
Dim returnValue As String = String.Empty
Try
Dim consString As String = ConfigurationManager _
.ConnectionStrings("conString").ConnectionString
Dim conn As New SqlConnection(consString)
Dim cmd As New SqlCommand("spx_CheckUserAvailability", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@UserName", userName.Trim())
conn.Open()
returnValue = cmd.ExecuteScalar().ToString()
conn.Close()
Catch
returnValue = "error"
End Try
Return returnValue
End Function
Wrap the function
In
It could be that the DOM hasn't loaded and the event isn't binding the first time through. The document.ready wrapper will ensure the DOM has loaded
write this function in keydown or keypress ratherthen keyup event may be it's working.