简体   繁体   中英

select the text in a text field when clicked?

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>

尝试:

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

This works for me in Opera, FF, IE

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

我只是在HTML中使用它:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM