开发者

select the text in a text field when clicked?

开发者 https://www.devze.com 2022-12-14 09:43 出处:网络
how can you so that the text in the text field is selected when the user clicks on the开发者_开发技巧 text input field?

how can you so that the text in the text field is selected when the user clicks on the开发者_开发技巧 text input field?

i have used this code:

  $("input[type=text]").focus(function() {
      $(this).select();
  });

but it doesnt work in safari. and in FF it works sometimes.


The select() method in jQuery simply triggers the select event on all matched objects. You need to do something fancier if you want to manipulate the selected range of text in a textbox. Modern browsers behave differently here.

The following code should work in Chrome, Firefox, IE, Safari, and Opera:

<input type="text" id="textBox" />
<script type="text/javascript">
$(document).ready(function(){
    function textBox_click(ev) {
        if (this.createTextRange) {
            // This is for IE and Opera.
            range = this.createTextRange();
            range.moveEnd('character', this.value.length);
            range.select();
        } else if (this.setSelectionRange) {
            // This is for Mozilla and WebKit.
            this.setSelectionRange(0, this.value.length);
        }
    }

    $('#textBox').click(textBox_click);
});
</script>


Try:

$("input[type=text]").focus().select();


This works for me in Opera, FF, IE

$("input[type=text]").focus(function() {
    this.select();
});


I just use this in my HTML:

... onclick="this.select()" 
0

精彩评论

暂无评论...
验证码 换一张
取 消