'How to add plus one position to setSelectionRange
I am trying to move cursor one more position to the right in input.
var start = this.selectionStart,
end = this.selectionEnd;
this.setSelectionRange(start, end);
This works for keeping position in the same place after input value changed, but iam trying to add one more position to it, because my format code add "-" character after 4 chars.
$("input[name=login-access-token]").keypress(function(event){
var start = this.selectionStart,
end = this.selectionEnd;
console.log(start);
var input = $(this).val();
input = input.replace(/[\W\s\._\-]+/g, '');
var split = 4;
var chunk = [];
for (var i = 0, len = input.length; i < len; i += split) {
split = 4;
chunk.push( input.substr( i, split ) );
}
var test = [];
chunk.forEach(element => {
test.push(element.match(/.{1,4}/g));
});
test.forEach(element => {
if(element.length!=4){
$(this).val(function() {
var out = chunk.join("-").toUpperCase();
if(out.length == 4 && event.keyCode != 8){
out += "-";
}
if(out.length == 9 && event.keyCode != 8 ){
out += "-";
}
return out;
});
}
});
this.setSelectionRange(start, end);
var selection = window.getSelection();
selection.addRange(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="text" name="login-access-token" placeholder="Code" />
var selection = window.getSelection();
selection.addRange(1); //not working :/
Solution 1:[1]
I solved it! Just add +1 to start and end which is values what we get from selectionStart.
if(out.length == 4 && event.keyCode != 8){
out += "-";
start = start+1;
end = end +1;
}
if(out.length == 9 && event.keyCode != 8 ){
out += "-";
start = start+1;
end = end +1;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SetAndGet |
