I want to have all the text selected when I give the focus to an element.
I used
$('.class-focusin').focusin(function(e) {
$(this).select();
});
But it's not the perfect behavior I want. When i click between two characters, the input value is not seleted, there is a cursor in the middle. I want the behavior of the url bar in chrome browser: you click and the cursor is replaced by the value selection
Feel free to test my problem in this fiddle: http://jsfiddle.net/XS6s2/8/
I want the text to be able to receive the cursor once selected. The answer selected, below is definitely what I wanted, Thanks
The HTMLInputElement. select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.
//Select all Input field on focus $("input"). select(); //Select Input field on focus whose type="text" $("input[type='text']"). select(); //Select input field using its id="input-field" $("#input-field"). select();
The :text selector selects input elements with type=text.
HTML | DOM Input Text select() Method The DOM Input select() method selects all the text content of a textarea or an input element which contains the text field. Syntax: element. select();
You could have a variable to see if the text has been selected or not:
http://jsfiddle.net/jonigiuro/XS6s2/21/
var has_focus = false;
$('.class-focusin').click(function(e) {
if(!has_focus) {
$(this).select();
has_focus = true;
}
});
$('.class-focusin').blur(function(e) {
has_focus = false;
});
I guess you have to wait for the browser to give focus to the element, then do your selection:
$('.class-focusin').focus(function(e) {
var $elem = $(this);
setTimeout(function() {
$elem.select();
}, 1);
});
Yuck. Or simply bind to the click event instead:
$('.class-focusin').click(function(e) {
$(this).select();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With