0

I am creating web application in asp.net. I have 5 text box which are asp controls. I want to get which text box having focus on that time and then when I am press "add" button, the "hello" text has to added to the particular text box which are got focused before pressed the "add" button.

I need Asp.net (with C# code) to move to my next step

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
  • Is this what you mean? http://stackoverflow.com/questions/497094/how-do-i-find-out-which-dom-element-has-the-focus – Mark Hughes Mar 25 '15 at 06:27

1 Answers1

0

Since the last focus will be on the Add button, you need to "remember" the TextBox before the Button is clicked.

Try to use onfocus() event.

<!-- Add a HiddenField control to "remember" the id of a TextBox -->
<asp:HiddenField ID="HiddenField1" runat="server" />  

<!-- Assign current focus to that hidden field -->
<asp:TextBox onfocus="document.getElementById('HiddenField1').value=this.id" ...>
<asp:TextBox onfocus="document.getElementById('HiddenField1').value=this.id" ...>

If that works, you will be able to get a value in code-behind as

string c = HiddenField1.Value;

if (!string.IsNullOrEmpty(c)) 
   if (c == "TextBox1")
      TextBox1.Text = "hi there";

Note: depends on your environment you might need to call ClientID (e.g. getElementById('<%=HiddenField1.ClientID%>')

UPDATE

As I told you above you might need to use HiddenField1.ClientID to find the HiddenField Control. When your source looks as

<input type="hidden" name="ctl00$MainContent$HiddenField1" id="MainContent_HiddenField1" /> 

<input name="ctl00$MainContent$TextBox1" type="text" id="MainContent_TextBox1" 
    onfocus="document.getElementById(&#39;HiddenField1&#39;).value=this.id" />    
<input name="ctl00$MainContent$TextBox2" type="text" id="MainContent_TextBox2" 
    onfocus="document.getElementById(&#39;HiddenField1&#39;).value=this.id" /> 

<input type="submit" name="ctl00$MainContent$Button1" value="Button" id="MainContent_Button1" />

That means that you use MasterPage and asp.net changes id of your control to MainContent_HiddenField1. So when you use document.getElementById('HiddenField1') it will not find such control because its id is different. You either need to use

document.getElementById('MainContent_Button1').value=this.id

which will work but might require changes if you remove master page or will move the textbox to other container

or use

document.getElementById('<%=HiddenField1.ClientID%>').value=this.id

which will automatically inject correct id (recommended asp.net way)

user2316116
  • 6,726
  • 1
  • 21
  • 35