简体   繁体   中英

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. I am providing a delete confirmation using the OnClientClick attribute of the <asp:button> .

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

<script type="text/javascript">
var username = document.GetElementByID(<%= txtUser.ClientID %>")
</script>

Now I want to use this username variable in the OnClientClick call. 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.

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. Make sure the assignment of username is after the textbox in the markup, or use something like 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM