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

后端 未结 30 3423
时光说笑
时光说笑 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:25

    If you set the value first and then set the focus, the cursor will always appear at the end.

    $("#search-button").click(function (event) {
        event.preventDefault();
        $('#textbox').val('this');
        $("#textbox").focus();
        return false;
    });
    

    Here is the fiddle to test https://jsfiddle.net/5on50caf/1/

提交回复
热议问题