Focus on the last Jquery character

Asked

Viewed 453 times

2

I need when the field gets the focus, the cursor to be in the last character. The way the cursor is at the beginning of the field even if 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); 
}   

2 answers

3


Uses the .setSelectionRange and gives it a number greater than the input length.

Something like that:

$("#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>
<input id="obsCampo" value="algum texto" />
<button>Clica aqui para focar o input</button>

  • Using boot it works but as the focus arrives in the field through a function did not work.

  • @Ezequieltavares must be doing something wrong. Take a look at the answer now with a function example after 3 seconds.

  • I edited the question with the full code already with the changes I tested.

  • as is it gets the focus through a function

  • @Ezequieltavares with more code now I understand your problem better. Two things: 1- Are you calling the .focus() before the event headset: it has to be the other way around. 2- As this input is created dynamically you have to use delegation. Example: http://jsfiddle.net/Sergio_fiddle/e4kv80pm/

  • perfect Die... worked round including in IE. hug

Show 1 more comment

1

Whenever you receive the focus, either by click, TAB key or other, 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>
<input type="text" id="obsCampo" value="texto" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.