开发者

Clearing Html textbox value permanently using Jquery

开发者 https://www.devze.com 2023-03-11 01:56 出处:网络
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 $(\

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 myO开发者_如何学运维bject = 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>")
        }
    });
}


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.


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("");
                    }
                });
            }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号