Focus on the last character Jquery

2

I need that when the field receives the focus, the cursor stays on the last character. The way the cursor is is at the beginning of the field even though the field is not empty.

function gravaObs(unidadeObs) {
    var gasObs = $('#obsGas_'+unidadeObs).val();
    swal({
        title: "Inserir Observações", 
        html: '<input type="text" id="obsCampo'+unidadeObs+'" class="col-xs-12 form-control" value="'+gasObs+'" /><br>',    
        confirmButtonText: "Salvar",
        confirmButtonColor: "#5cb85c",
        cancelButtonText: "Cancelar",
        cancelButtonColor: "#d9534f",
        showCancelButton: true,
        onOpen: function () {

            $('#obsCampo'+unidadeObs).focus();

            $('#obsCampo'+unidadeObs).on('focus', function() {
                var pos = this.value.length * 2;
                this.setSelectionRange(pos, pos);
            });
        }
    }).then(function(){
        var resultado = $('#obsCampo'+unidadeObs).val();
        console.log(resultado);
        $('#obsGas_'+unidadeObs).val(resultado);                
    }).catch(swal.noop); 
}   
    
asked by anonymous 19.08.2017 / 23:14

2 answers

3

It uses .setSelectionRange and gives it a number greater than the length of the input.

Something like this:

$("#obsCampo").on('focus', function() {
  var pos = this.value.length * 2;
  this.setSelectionRange(pos, pos);
});

$('button').click(function() {
  $("#obsCampo").focus()
});

// ou de 3 em 3 segundos
setInterval(() => $("#obsCampo").focus(), 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="obsCampo" value="algum texto" />
<button>Clica aqui para focar o input</button>
    
19.08.2017 / 23:19
1

Whenever you receive the focus, either by click, TAB key or another, the cursor will be positioned after the last character:

$("#obsCampo").on("focus click",function(){
	var pos = this.value.length+1;
	this.setSelectionRange(pos,pos);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="obsCampo" value="texto" />
    
20.08.2017 / 03:24