简体   繁体   中英

jQuery move cursor to end of text input

Currently I have an input box which has the value "Current Website"

When they click it I run this function:

function clearMeHttp(formfield) {
    if (formfield.defaultValue == formfield.value) {
        formfield.value = "http://";
    }
};

It works fine if you click into the box, but if you tab into the box it just highlights the word "http://" which defeats the purpose of it unless they hit the right arrow key which I want to avoid.

Thanks!

Here's the other code: <input onblur="restoreMe(this)" onfocus="clearMeHttp(this)" type="text" class="fade" name="website" value="Current website">

restoreMe just fades default value back in gently with jquery

I have changed your code a bit, but uses jquery events instead of inline html.

Full script used:

var defaultVal = 'Current website';
$(function() {

    $('.urlCheck').focus(function(e) {
        if ($(this).val() == "http://" || $(this).val() == '' || $(this).val() == defaultVal) {
            $(this).val('http://');
            $(this).select(false);

        }
    });

    $('.urlCheck').keyup(function(e) {
        if ($(this).val() == "http://" || $(this).val() == '' || $(this).val() == defaultVal) {
            $(this).val('http://');
        }
    });

    $('.urlCheck').blur(function(e) {
        $(this).val(defaultVal);
    });

});

Working Link : http://jsfiddle.net/29gks/6/

The keyup event is the override for Chrome and Safari

You haven't use jquery so I follow you.

script:

function clearMeHttp(formfield) {
    if (formfield.defaultValue == formfield.value) { 
         formfield.value="";        
         formfield.style.padding="0 0 0 40";
         document.getElementById("http").style.display="block";
    }
}; 

html:

<label id="http" style="float:left;position:absolute;display:none;">http://</label>
<input onblur="restoreMe(this)" onfocus="clearMeHttp(this)" type="text" class="fade" name="website" value="Current website">

That catch your requirement but may be not the way you want

You need to use setSelectionRange() (or selectionStart and selectionEnd ) on most browsers and some TextRange shenanigans on IE < 9.

Here's my previous answer to the same question: How to place cursor at end of text in textarea when tabbed into

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