Search code examples
c#jquerywebmethod

Textbox value not changing in webmethod result


Here Webmethod return value correctly and the label value change as per the condition but the value of txtusername is not changing

<div class="col-sm-6">
<p style="margin: 0 0 5px 0;"><b>User Name</b>&nbsp;<span class="pull-right">
    <asp:Label ID="usernamelbl" Font-Size="X-Small" runat="server"></asp:Label></span></p>
<asp:TextBox ID="txtUserName" CssClass="form-control" runat="server" placeholder="Enter UserName" 
OnChange="CheckUserName(this)"></asp:TextBox>
</div>

Jquery

 function CheckUserName(oName) {
                PageMethods.UserNameChecker(oName.value, OnSucceeded);
            }
            function OnSucceeded(result, userContext, methodName) {
                lbl = document.getElementById('<%=usernamelbl.ClientID %>');
                lbl1 = document.getElementById('<%=txtUserName.ClientID %>');
                if (methodName == "UserNameChecker") {
                    if (result == true) {
                        lbl.innerHTML = 'Try Another Username';
                        lbl.style.color = "red";
                        $('<%=txtUserName.ClientID %>').val('');
 lbl1.style.color = "Blue";
                    }
                    else {
                        lbl.innerHTML = '';
                    }
                }
            }

this works (lbl1.style.color = "Blue";)fine but the value is not changeing. I also try lbl1.innerHTML = ''; but failed Please Help me


Solution

  • use

    lbl1.value = "something"
    

    for the way of you writing, you did not fully utilise jquery

    instead of

    lbl1 = document.getElementById('<%=txtUserName.ClientID %>');
    

    you can write as

    lbl1 = $('input[id$="txtUserName"]');
    

    id$ means that id that end with

    then you can use lbl1.val("something") to populate it

    and you can abandon the below script,

    $('<%=txtUserName.ClientID %>').val('');
    

    if you insist of using it, you need to add

    $('#' +'<%=txtUserName.ClientID %>').val('');