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()"
精彩评论