Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .focus() is highlighting all pre-filled text

HTML

<input id="formloginusername" type="text" name="username" placeholder="Username" value="Pre-filled-from-database"></input>

JS:

$(document).ready(function() {
    $("#formloginusername").focus();
});

Problem:

The text "Pre-filled-from-database" is highlighted. I only want the cursor to show in the field as if the user had clicked it after the filled text.

Thanks!

like image 831
GiantDuck Avatar asked Nov 14 '12 00:11

GiantDuck


People also ask

What does jQuery focus do?

jQuery focus() Method The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs. Tip: This method is often used together with the blur() method.

How to focus element using jQuery?

The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.

How do you highlight input field on focus?

To auto-highlight an input field on focus with JavaScript, we can call select on the element when the focus event is emitted. to add an input with a value filled in. to select the input with document. querySelector .

How do you highlight a text field?

Select text with the mouse buttonDouble-clicking a word highlights the word and triple-clicking a word highlights the full line or paragraph of text.


1 Answers

Here's a nifty little trick...

$(document).ready(function() {
    var $field = $("#formloginusername"),
        oldVal = $field.val();
    $field.focus().val('').val(oldVal);
});

DEMO: http://jsfiddle.net/X7Y8S/

like image 158
ahren Avatar answered Sep 28 '22 01:09

ahren