[英]How to use a javascript variable in the OnClientClick attribute of a ASP.NET control
I have a single textbox txtUser
where a user can input a username, and there is a Delete button beside this textbox. 我有一个文本框txtUser
,用户可以在其中输入用户名,此文本框旁边有一个删除按钮。 I am providing a delete confirmation using the OnClientClick
attribute of the <asp:button>
. 我使用<asp:button>
的OnClientClick
属性提供删除确认。
The message is: Are you sure you want to delete this user? 消息是: 您确定要删除此用户吗? This works. 这有效。
I want to change this message to Are you sure you want to delete 'username'? 我想将此消息更改为您确定要删除“用户名”吗? by getting the value of the username from the textbox using the GetElementByID("<%= txtUser.ClientID %>")
and storing it in a variable user
通过使用GetElementByID("<%= txtUser.ClientID %>")
从文本框中获取用户名的值并将其存储在变量user
<script type="text/javascript">
var username = document.GetElementByID(<%= txtUser.ClientID %>")
</script>
Now I want to use this username
variable in the OnClientClick call. 现在我想在OnClientClick调用中使用此username
变量。 I tried something like this, but it didn't work: 我尝试过类似的东西,但它不起作用:
<asp:Button ID="BtnDelete" runat="server"
OnClientClick="return confirm('Are you sure you want delete "+username+"');">
Delete</asp:Button>
Almost there... 快好了...
<script type="text/javascript">
var username = document.getElementByID("<%= txtUser.ClientID %>").value;
</script>
then 然后
<asp:Button ID="BtnDelete" runat="server" OnClientClick="return confirm('Are you sure you want delete '+username+'?');">Delete</asp:Button>
Should do it. 应该这样做。 You need to get the value of the text box, and then append the username to the are you sure string, not append it to the ASP control. 您需要获取文本框的值,然后将用户名附加到您确定的字符串,而不是将其附加到ASP控件。
As a word of possible warning, if attempt to get the value of the textbox and assign it to username
before the textbox is rendered, it will result in an error. 作为可能警告的一个词,如果尝试获取文本框的值并在呈现文本框之前将其分配给username
,则会导致错误。 Make sure the assignment of username
is after the textbox in the markup, or use something like window.onload
. 确保username
的分配位于标记中的文本框之后,或使用window.onload
。
This is a bit clearer for the next developer who wants to look at what you did 对于想要了解您所做的事情的下一位开发人员来说,这一点更为清晰
<script type="text/javascript">
function getUserName()
{
var userTextBoxId ='<%= txtUser.ClientID %>';
return document.getElementByID(userTextBoxId).value;
}
</script>
Then 然后
<asp:Button ID="BtnDelete" runat="server" OnClientClick="return confirm('Are you sure you want delete ' + getUserName() + '?');">Delete</asp:Button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.