Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attributes.Add Onclick Event in c# code behind

I have two textboxes tbxProdAc & txtbxHowMany. I would like to write a bit of code in the code behind so that when I enter text in one, any text that may have been in the other is removed.

How would one go about achieving this and in which event should I place it?

I have tried to use

txtbxHowMany.Attributes.Add("onclick", "document.getElementById('tbxProdAC').innerText='';");

in the page load event but twithout success...should this be in the pre_init?

As you can probalby tell, complete novice at work here.

like image 715
MrDean Avatar asked Nov 30 '09 13:11

MrDean


People also ask

How do you add onclick event from code behind?

Show activity on this post. protected void btn_Click(object sender, EventArgs e) { do anything... } Show activity on this post. If you want to attach button's event dynamically, you want to use button's CommandName, and catch the event in ItemCommand event.

What is event in Onclick?

The onclick event occurs when the user clicks on an element. In HTML: <element onclick="myScript"> In JavaScript: object.


2 Answers

First off, make sure that when the page has been generated that the ID is still "tbxProdAC" if this is a .Net control, the ID would have been changed. In this case you can use a class.

Try the following, - This uses JQuery - you will need to include that

txtbxHowMany.Attributes.Add("onclick", "$('#tbxProdAC').val('');"); 

Add the following to the Head Section of your page.

 <script type="text/javascript" src="jquery.js"></script> 

And you can get the JQuery.Js file from here: http://docs.jquery.com/Downloading_jQuery#Download_jQuery

And Why: https://stackoverflow.com/questions/308751/why-use-jquery

like image 179
LiamB Avatar answered Oct 16 '22 11:10

LiamB


ASP.NET Changes the ID's of the generated controls, so probably your tbxProdAc will have its id changed to something else. You need to run the app once, view source and know the Id of your control and then replace the "tbxProdAc" with the new Id in your

txtbxHowMany.Attributes.Add("onclick", "document.getElementById('tbxProdAC').innerText='';"); 

and yes it will work onLoad.

like image 1
TheOne Avatar answered Oct 16 '22 11:10

TheOne