Reputation: 726
I am currently wanting to focus the first input element, without selecting the preset value text inside the input element. How can I focus my input element, and then deselect the text inside it? My current focus jQuery is as follows.
$(document).ready(function() {
$("input[name='title']").focus();
});
Upvotes: 9
Views: 13168
Reputation: 986
Would like to add some enhanced solution that also cares of the actual caret positioning on deselect.
I utilized the following input
element methods:
<input (blur)="onLocalFocusOut()" (click)="onInputClick($event)" (mousedown)="onMouseDown($event)" />
And the methods look as the following:
public onInputClick(event: MouseEvent): void {
if (!this._initialSelectAll) {
(event.target as HTMLInputElement).select();
this._initialSelectAll = true;
}
}
public onMouseDown(event: MouseEvent): void {
if (this._initialSelectAll) {
(event.target as HTMLInputElement).selectionStart = (event.target as HTMLInputElement).selectionEnd = 0;
}
}
public onLocalFocusOut(): void {
this._initialSelectAll = false;
this.onFocusChange(false);
}
Such a setup ensures that for each first click
within an input
element all of the field contents will be selected. Any subsequent click
will clear the selection and position the caret at the actual mouse click coordinates. Whenever the input
element will loose the focus this logic will be re-initialized.
The html
and code
are written for angular 2+
but it's quite simple to adapt it to any other coding framework.
Upvotes: 0
Reputation: 8917
This is based on Danilo Valente's answer above. I found that on Chrome I had to use a tiny delay before calling this.selectionEnd = this.selectionStart
, otherwise the input text would remain selected:
This works for me on Chrome, Firefox, Safari and IE (tested IE 10)
$("input").focus(function() {
var input = this;
setTimeout(function() { input.selectionStart = input.selectionEnd; }, 1);
});
Here's a demo: http://jsfiddle.net/rangfu/300ah0ax/2/
Upvotes: 4
Reputation: 486
Its not briliant buy may help you
Basic : Overwrite what is already there...
$(document).ready(function() {
$('#t1').focus();
$('#t1').val($('#t1').val());
});
Upvotes: -2
Reputation: 305
$(document).ready(function() {
$("input[name='title']").focus();
$("input[name='title']").val($("input[name='title']").val());
});
Upvotes: 9
Reputation: 102428
$("input[name='title']").focus(function()
{
var elem = $(this);
elem.val(elem.val());
});
Upvotes: 0
Reputation: 11352
You can use the selectionStart
and selectionEnd
properties:
$(document).ready(function() {
$("input[name='title']").each(function(){
this.focus();
this.selectionEnd = this.selectionStart;
});
});
Upvotes: 12