在javascript中引用输入(type = password)(ASP.NET)

时间:2011-07-12 21:42:59

标签: javascript asp.net input passwords

我有这个:

<input type="password" id="txtPassword" name="txtPassword" />

我想做这样的事情:

var password = document.getElementById("<%= txtPassword.ClientID %>").value();

但它告诉我“'txtPassword'未被声明。”我试过这个:

var pswd = $find('txtPassword').value();

但是我得到''null'是null或者不是对象。所以然后我尝试了这个:

var pswd = $find('txtPassword').value();

但是我得到了同样的东西。我的输入控件位于这个混乱中:

    <asp:Panel ID="pnlPassword" style="display: none" runat="server">
<div class="PasswordPopup">
            <div id="PopupHeader">&nbsp;</div>
            <div class="Controls">
                <center><table><tr>
                    <td>Please enter your password:</td><td><input type="password" id="txtPassword" name="txtPassword" /></td></tr>
                <tr><td>&nbsp;</td>
                    <td><asp:button name="btnOK" id="btnOK" runat="server" text="OK" />&nbsp;&nbsp;<asp:button id="btnCancel" runat="server" text="Cancel" /></td></tr></table></center>
            </div>
 </div>
</asp:Panel>

如何在我的javascript函数中引用该输入控件?

谢谢,

杰森

3 个答案:

答案 0 :(得分:2)

您需要修改密码输入runat="server"才能从服务器脚本中访问...

<input runat="server" type="password" id="txtPassword" name="txtPassword" />

或者,您可以使用带有TextBox ...

的ASP.NET TextMode="Password"控件
<asp:TextBox runat="server" id="txtPassword" TextMode="Password" />

答案 1 :(得分:1)

你没有为你指定runat =“server”,所以这应该足够了:

  var password = document.getElementById("txtPassword").value();

如果您想在服务器代码中使用它,请添加runat =“server”

答案 2 :(得分:1)

当控件在HTML中呈现时,服务器端控件(即runat ='server')将生成id,而非服务器端控件将按原样生成。

使用Quintin的解决方案,您应该能够使用Control.ClientID来访问您的控件。

你遇到麻烦的原因是语法。

Solution1(Quintin's):

  • 将runat ='server'添加到您的控件
  • var password = document.getElementById(“&lt;%= txtPassword.ClientID%&gt;”)。value;

Solution2(使用jQuery):

  • jQuery不需要命名元素的查找符号
  • var password = $('txtPassword')。value;

Solution3(使用DOM):    - var password = document.getElementById('txtPassword')。value;