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

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

    I've tried the following with quite great success in chrome

    $("input.focus").focus(function () {
        var val = this.value,
            $this = $(this);
        $this.val("");
    
        setTimeout(function () {
            $this.val(val);
        }, 1);
    });
    

    Quick rundown:

    It takes every input field with the class focus on it, then stores the old value of the input field in a variable, afterwards it applies the empty string to the input field.

    Then it waits 1 milisecond and puts in the old value again.

提交回复
热议问题