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

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

    Here’s a jsFiddle demo of my answer. The demo uses CoffeeScript, but you can convert it to plain JavaScript if you need to.

    The important part, in JavaScript:

    var endIndex = textField.value.length;
    if (textField.setSelectionRange) {
       textField.setSelectionRange(endIndex, endIndex);
    }
    

    I’m posting this answer because I already wrote it for someone else who had the same question. This answer doesn’t cover as many edge cases as the top answers here, but it works for me, and has a jsFiddle demo you can play with.

    Here is the code from the jsFiddle, so this answer is preserved even if the jsFiddle disappears:

    moveCursorToEnd = (textField) ->
      endIndex = textField.value.length
      if textField.setSelectionRange
        textField.setSelectionRange(endIndex, endIndex)
    
    jQuery ->
      $('.that-field').on 'click', ->
        moveCursorToEnd(this)
    
    :

    Try clicking in the text field. The cursor will always jump to the end.

    body {
        margin: 1em;
    }
    
    .field {
        margin-bottom: 1em;
    }
    

提交回复
热议问题