select text in TextBox from code?

G

Guest

Is there a way to mark the text in a TextBox control as selected so when the
user types a new value the existing text is replaced?

Thanks
 
B

Bruno Alexandre

just using javascript and add the event OnFocus on the textbox

you can implement in many ways:

when the user focus the textbox you delete all the value and present it as
new textbox
or when the user focus the textbox you delete all and if the user did not
changed the value you paste the old value back in the textbox


imagine that you have 2 textboxs called TextBox1 and TextBox2

onPageLoad add the onfous and onblur event to the textbox like:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
TextBox1.Attributes.Add("onfocus", "saveValue(this);")
TextBox1.Attributes.Add("onblur", "getValue(this);")
TextBox2.Attributes.Add("onfocus", "saveValue(this);")
TextBox2.Attributes.Add("onblur", "getValue(this);")
' for testing propose let's add some text on it
TextBox1.Text = "old value 1"
TextBox2.Text = "old value 2"
End Sub


and add the really simple javascript function:
<script language="javascript" type="text/javascript">
var oldValue = ''; // it will save our old values

function getValue( v ) {
if(v.value == '')
v.value = oldValue;
}
function saveValue( v ) {
oldValue = v.value;
v.value = '';
}
</script>


hope it helps
 
G

Guest

Hi Bruno

Well, I'm setting focus from code behind already. Would just like to
highlight the existing text and let user choose to leave it or delete it by
typing a new value. Is it possible to trigger Ctrl-A from javascript which
would select everything in the TextBox?

Thanks.
 
B

Bruno Alexandre

for that you use javascript

document.getIdFromElement("Textbox1").select();
 
G

Guest

Thanks for the tip Bruno,

sorry, I'm still new at js from ASP.NET, how would I call this from
codebehind in pageload?

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top