Animesh D
Animesh D

Reputation: 5002

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>

Upvotes: 1

Views: 4186

Answers (2)

Kiarash
Kiarash

Reputation: 1919

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>

Upvotes: 1

Steven V
Steven V

Reputation: 16595

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.

Upvotes: 2

Related Questions