将文本框值传递给javascript函数

Passing textbox value to javascript function

本文关键字:javascript 函数 值传 文本      更新时间:2023-09-26

我的asp.net页面中有一个Js函数,如下所示:

 function LoginPopup(username,password) {     
        alert(username);
        alert(password);
        username = username.val();
        password = password.val();
}

我是这样使用的:

<asp:Button ID="btnLogin" runat="server" UseSubmitBehavior="false" OnClientClick="LoginPopup('<%# UsernameTextBox.ClientID %>', '<%# PasswordTextBox.ClientID %>');  return false;"
                                    CssClass="login-button" Text="<%$ Resources: HRGELoggedOutMaster, Login %>">
                                </asp:Button>

但我看到LoginPopup得到的是"<%#UsernameTextBox.ClientID%>",而不是UsernameTextBox的客户端Id。我想将UsernameTextBox和PasswordTextBox值传递给LoginPoup。

请提出建议。

你能试试这个吗,document.getElementById()

function LoginPopup(username,password) {    
    alert(username);
    alert(password);
    username = document.getElementById(username).value;
    password = document.getElementById(password).value;
}

更正了ClientID语法:

<asp:Button ID="btnLogin" runat="server" UseSubmitBehavior="false" OnClientClick="LoginPopup('<%=UsernameTextBox.ClientID %>', '<%=PasswordTextBox.ClientID %>');  return false;"
                                CssClass="login-button" Text="<%$ Resources: HRGELoggedOutMaster, Login %>">
                            </asp:Button>

如果这不起作用,你可以尝试这种方式,你无论如何都没有使用服务器端的按钮:

    <input type="button" onclick="LoginPopup('<%=UsernameTextBox.ClientID %>', <%=PasswordTextBox.ClientID %>')" />

在js中(我假设您使用jQuery):

 function LoginPopup(username,password) {  
    username = $('#' + username).val();
    password = $('#' + password).val();
    // ...
}

如果您使用Gridview,请尝试以下示例方式

<ItemTemplate>
              <asp:LinkButton ID="lnkgettext" runat="server" OnClientClick='<%# String.Format("return callme({0})", (((GridViewRow)Container).FindControl("txtName") as TextBox).ClientID) %>'
                        Text="Gettextboxvalue"></asp:LinkButton>
</ItemTemplate>

要测试的javascript函数是-

function callme(cntrl) {
            alert(cntrl.id);
            alert(cntrl.value);
            return false;
}