Set mouse focus and move cursor to end of input using jQuery

后端 未结 19 1849
醉话见心
醉话见心 2020-12-04 06:42

This question has been asked in a few different formats but I can\'t get any of the answers to work in my scenario.

I am using jQuery to implement command history wh

相关标签:
19条回答
  • 2020-12-04 07:26

    It looks a little odd, even silly, but this is working for me:

    input.val(lastQuery);
    input.focus().val(input.val());
    

    Now, I'm not certain I've replicated your setup. I'm assuming input is an <input> element.

    By re-setting the value (to itself) I think the cursor is getting put at the end of the input. Tested in Firefox 3 and MSIE7.

    0 讨论(0)
  • 2020-12-04 07:27

    Here is another one, a one liner which does not reassign the value:

    $("#inp").focus()[0].setSelectionRange(99999, 99999);
    
    0 讨论(0)
  • 2020-12-04 07:27

    It will focus with mouse point

    $("#TextBox").focus();

    0 讨论(0)
  • 2020-12-04 07:28

    It will be different for different browsers:

    This works in ff:

        var t =$("#INPUT");
        var l=$("#INPUT").val().length;
        $(t).focus();
    
        var r = $("#INPUT").get(0).createTextRange();
        r.moveStart("character", l); 
        r.moveEnd("character", l);      
        r.select();
    

    More details are in these articles here at SitePoint, AspAlliance.

    0 讨论(0)
  • 2020-12-04 07:29

    set the value first. then set the focus. when it focuses, it will use the value that exists at the time of focus, so your value must be set first.

    this logic works for me with an application that populates an <input> with the value of a clicked <button>. val() is set first. then focus()

    $('button').on('click','',function(){
        var value = $(this).attr('value');
        $('input[name=item1]').val(value);
        $('input[name=item1]').focus();
    });
    
    0 讨论(0)
  • 2020-12-04 07:30

    like other said, clear and fill worked for me:

        var elem = $('#input_field');
        var val = elem.val();
        elem.focus().val('').val(val);
    
    0 讨论(0)
提交回复
热议问题