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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

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();
Husni Salax
  • 1,968
  • 1
  • 19
  • 29
  • @DemenyiNorbert I've edited my solution pls, check it.. you should use focus() function – Husni Salax Aug 01 '17 at 21:30
  • @DemenyiNorbert Try this: https://stackoverflow.com/questions/18931936/call-javascript-function-from-c-sharp – Husni Salax Aug 02 '17 at 09:29
  • 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. – Demenyi Norbert Aug 02 '17 at 10:20
  • @DemenyiNorbert Here is an example which works this method:https://jsfiddle.net/5mad9dpr/ so, I've also edited my solution above – Husni Salax Aug 02 '17 at 10:33
  • This works fine but the problem when I use onclick="Button1_Click" can`t call C# codes, . Therfore I would like to use – Demenyi Norbert Aug 02 '17 at 19:55
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);
hardkoded
  • 18,915
  • 3
  • 52
  • 64