Use JavaScript to place cursor at end of text in text input element

后端 未结 30 3912
时光说笑
时光说笑 2020-11-22 02:48

What is the best way (and I presume simplest way) to place the cursor at the end of the text in a input text element via JavaScript - after focus has been set to the element

30条回答
  •  半阙折子戏
    2020-11-22 03:34

    Set the cursor when click on text area to the end of text... Variation of this code is...ALSO works! for Firefox, IE, Safari, Chrome..

    In server-side code:

    txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")
    

    In Javascript:

    function sendCursorToEnd(obj) {
        var value =  $(obj).val(); //store the value of the element
        var message = "";
        if (value != "") {
            message = value + "\n";
         };
        $(obj).focus().val(message);
        $(obj).unbind();
     }
    

提交回复
热议问题