jQuery move cursor to end of text input

2019-07-26 04:36发布

问题:

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

回答1:

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



回答2:

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



回答3:

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