I have two text fields in my web page. The user is supposed to enter two numbers seperated by a hyphen ("-") character. The numbers may be between 1 and 10 digits each. I need the cursor to move to the next field when the user presses the hyphen key.
I can easily move the cursor using $('#txtField2').focus()
. However, I still have the problem that the hyphen character remains in the first text field. How can I easily supress the hyphen from appearing in the first text field?
I have two text fields in my web page. The user is supposed to enter two numbers seperated by a hyphen ("-") character. The numbers may be between 1 and 10 digits each. I need the cursor to move to the next field when the user presses the hyphen key.
I can easily move the cursor using $('#txtField2').focus()
. However, I still have the problem that the hyphen character remains in the first text field. How can I easily supress the hyphen from appearing in the first text field?
5 Answers
Reset to default 9HTML
<form>
<input type='text' class='num' />
<input type='text' class='num' />
</form>
JavaScript
$('.num:first').keydown(function (event) {
// check for hyphen
if (event.which === 189) {
event.preventDefault();
$(this).next('.num').focus();
}
});
Live demo
Assuming a simplified html of:
<form action="#" method="post">
<fieldset>
<label for="numOne">Number:</label>
<input type="text" id="numOne" name="numOne" />
<input type="text" id="numTwo" name="numTwo" />
</fieldset>
</form>
The following should work, or serve as an example:
$('#numOne').keypress(
function(e){
if (e.which == 45) {
$(this).next('input:text').focus();
return false; // prevents the '-' being entered.
}
});
JS Fiddle
Incidentally, I used $(this).next('input:text')
rather than an id-based selector to allow for more general application and re-use.
References:
keypress()
,next()
.
I'd do it like this:
$('#input1').keypress(function(e) {
if(e.keyCode == 45) {
e.preventDefault();
$('#input2').focus();
}
});
see live example here: http://jsfiddle.net/wjNP3/2/
Maybe this can help you:
HTML
<div>
<p>Insert Your Number:</p>
<input type="number" value="" id="first" >
<input type="number" value="" id="second" >
<input type="number" value="" id="third" >
<input type="submit" id="submit">
</div>
jQuery
$("#first").on("keypress", function(){
if($("#first").val().length == 4){
$("#second").focus();
}
})
$("#second").on("keypress", function(){
if($("#second").val().length == 4){
$("#third").focus();
}
})
$("#third").on("keypress", function(){
if($("#third").val().length == 5){
$("#submit").focus();
}
})
OR you can check Live DEMO by CLICK HERE!
you could "listen" to that character and just focus the other field and prevent it from inputing