1

Here is my Javascript function:

<script type="text/javascript">

    function SelectionTextBox()
    {

            document.getElementById("TextBox1").select();

    }

</script>

Here I call the function on the button:

ScriptManager.RegisterClientScriptBlock(this, GetType(), "t ", "SelectionTextBox();", true);

I want to select text in my TextBox1 on button click but it does not work.

2
  • use focus() function Commented Aug 1, 2017 at 21:34
  • Are those controls inside another user control or a master page? Commented Aug 2, 2017 at 11:16

2 Answers 2

3

var selectButton = document.getElementById("mySelectBtn");
var textBox = document.getElementById("myTextBox");
selectButton.addEventListener('click', SelectionTextBox = function(){

textBox.focus();
textBox.select();

});
<input type='button' id='mySelectBtn' value='Select'/>
<input type='text' id='myTextBox' value='testString'/>

Try use this code for handling Javascript function by Code behind (C#):

Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","SelectionTextBox();",true);

Instead:

ScriptManager.RegisterClientScriptBlock(this, GetType(), "t ", "SelectionTextBox();", true);

JavaScript should be:

var input = document.getElementById('myTextInput');

input.focus();
input.select();
Sign up to request clarification or add additional context in comments.

5 Comments

@DemenyiNorbert I've edited my solution pls, check it.. you should use focus() function
Sorry but I tried this before I posted my question. I can`t realize what is the problem. I tried the alert() method which is worked with button but the selection does not work.
@DemenyiNorbert Here is an example which works this method:jsfiddle.net/5mad9dpr so, I've also edited my solution above
This works fine but the problem when I use onclick="Button1_Click" cant call C# codes, <input type='button' id='Button1' onclick="Button1_Click" />. Therfore I would like to use <asp:Button ID="Button1" instead of <input type='button' but this way cant call the javascript function.
0

You are getting that because your script is being executed before your controls are rendered. Just use RegisterStartupScript and it will work.

RegisterStartupScript will write your script just before closing the form tag, so you'll be safe there.

ScriptManager.RegisterStartupScript(this, GetType(), "t ", "SelectionTextBox();", true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.