Reputation: 2091
I have a <%: Html.TextBoxFor(model=>model.UserName)%>
. Here I'm checking wheather user name is available or not. If it's not available then I need to clear the TextBox. I used the query $("#UserName").val("");
. But after the event completion again the text box getting the value. Can anyone help me?
UPDATE: Additional Javascript code from comments:
function CheckAvailability() {
$.post("/WebTeamReleaseDB/CheckAvailability", {
Username: $("#UserName").val()
}, function(data) {
var myObject = eval('(' + data + ')');
var newid = myObject;
if (newid == 1) {
$("#usernamelookupresult").html("<font color='green'>Available :-D</font>")
} else {
$("#UserName").val("");
$("#usernamelookupresult").html("<font color='red'>Taken :-(</font>")
}
});
}
Upvotes: 1
Views: 2071
Reputation: 2091
I got the answer for my problem.
HTML code:
<%: Html.TextBoxFor(model=>model.UserName,new { @onchange="CheckAvailability()" }) %>
Javascript Code:
function CheckAvailability() {
var value;
if (document.getElementById("UserName").value == "") {
$("#usernamelookupresult").html("");
alert("Please Enter User Name");
}
else {
$.post("/WebTeamReleaseDB/CheckAvailability",
{
Username: $("#UserName").val()
},
function (data) {
var myObject = eval('(' + data + ')');
var newid = myObject;
value = myObject;
if (newid == 1) {
$("#usernamelookupresult").html("<font color='green'>Available :-D</font>")
}
else if (newid == 2) {
$("#usernamelookupresult").html("<font color='red'>UserName Invalid! :-(</font>")
}
else {
$("#usernamelookupresult").html("<font color='red'>Taken :-(</font>")
$("#UserName").val("");
}
});
}
}
Upvotes: 0
Reputation: 19413
When you use <%: Html.TextBoxFor(model=>model.UserName)%>
, it may be rendering to the page as <input name="UserName">
, so $("#UserName").val("");
is not finding it, as there is no id="UserName".
One possible solution: use <%: Html.TextBoxFor(model=>model.UserName, new { id = "UserName" })%>
, which should render to the page as <input name="UserName" id="UserName">
. After that, $("#UserName").val("");
should work, since the textbox now has that id attribute.
Upvotes: 1