0

The following code sets the focus on a specific textbox when the page loads. How do I select all the text in the textbox?

<script type="text/javascript">

        $(document).ready(function () {
            $(function () {
                var isPostBack = $("#IsPostBack").val();
                if (isPostBack == 'True') {
                    $('#MyElement').focus();
                }
            });
        });

</script>

Using function () { $(this).select(); } inside focus doesn't seem to work for me. In fact, it prevents the textbox from being selected at all.

As per another post, I tried the following but it did not work.

$(document).ready(function () { $(function () { var isPostBack = $("#IsPostBack").val(); if (isPostBack == 'True') { $('#Pupils4YOPreK').focus(function () { $(this).select(); }); } }); });

navig8tr
  • 1,724
  • 8
  • 31
  • 69

3 Answers3

1

Try this: (put this inside document ready function)

$('#MyElement').focus(function () {
    $('#MyElement').select().mouseup(function (e) {
        e.preventDefault();
        $(this).unbind("mouseup");
    });
});
TheProvost
  • 1,832
  • 2
  • 16
  • 41
0

Try this:

$(document).ready(function () {
    $(function () {
        var isPostBack = $("#IsPostBack").val();
        if (isPostBack == 'True') {
            $('#MyElement').on('mouseup', function() { $(this).select(); });
        }
    });
});
Fergoso
  • 1,584
  • 3
  • 21
  • 44
  • This works but has a major flaw. If you click on it it will always select all of the text. What if you only want to select a part of the string? – TheProvost Oct 30 '14 at 03:39
  • `live` was deprecated and removed in jQuery 1.9. Please do not suggest it. Use [`.on()`](http://api.jquery.com/on/) to attach event handlers – Ram Oct 30 '14 at 03:42
  • @Fergoso, copied and pasted this but it doesn't seem to work for me. Now the element isn't even being focused. – navig8tr Oct 30 '14 at 03:46
  • @TheProvost: Explain more... Is that a standard word you're talking about or is it the first word, etc... – Fergoso Oct 30 '14 at 03:51
  • @Fergoso For example the textbox has the phrase "This is a text", Your code will select everything fine on initial focus. But what if i want to select on the words this is? everytime i click on the text box to get it it will select everything since im focusing on it. Thus you have to take the functionality off once your done initializing it for the first time. Check my answer above. – TheProvost Oct 30 '14 at 03:57
0

You have to use only one document ready.

 <script type="text/javascript">
        $(document).ready(function () {
            var isPostBack = $("#IsPostBack").val();
            if (isPostBack == 'True') {
               $('#MyElement').focus(function(){ 
                   $(this).select();
               });
            }
        });
    </script>
Mad Angle
  • 2,347
  • 1
  • 15
  • 33