Reputation: 321
I'm not very experienced at javascript or jquery. I need to figure out whether the user's cursor is in the last position of a text input field with a maxlength of 3 on key up. If so, switch focus to the next field. I've seen this done a lot on forms so I think everyone can understand the semi common functionality I'm looking for. The input fields in question are not of type text, but of type tel
I tried to find an answer to this question here, but I couldn't understand any of the answers to what might be a similar question that I'm asking, but not exactly the same. For example, it mentions selectionStart and selectionEnd but I can't find where these are really explained. It seems to me like they involve selected text, but that's not what I want.
I want this to be checked while the user is typing. Here's what I have tried just to see if I can get a correct value back, but it returns undefined.
$("#phone1").keyup(function(){
var phone = $("#phone1");
alert(phone.selectionEnd);
});
Sorry if I don't understand some of this. Any assistance would be greatly appreciated. Thanks.
Upvotes: 0
Views: 1728
Reputation: 882
Basically, the jquery event that you should bind is 'change' event, this will fire on every change that will occur like new input, or delete input etc.
e.g.
(function(){
$('#telNo').on('input' , function(){
if($(this).val().length == $(this).attr('maxlength'))
$(this).next('input').focus();
});
})();
in above code, this code will shift the focus onto the next input, regardless of type
$(this).next('input').focus();
and the HTML markup should be like this:
<input type="tel" maxlength="4" id="telNo">
<input type="text" maxlength="4" id="text">
Here is a working fiddle
Upvotes: 0
Reputation: 277
is this what you are looking for?
(function ($, undefined) {
$.phone1.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
$("#phone1").on('keypress', function(e){
var key = String.fromCharCode(e.which);
if(key === '*') {
var position = $(this).getCursorPosition();
console.log(position);
} else {
return false;
}
});
font: Get keyup position using jquery is pretty similar I think..
Upvotes: 0