Raja Shekar Raja Shekar - 6 months ago 14
Javascript Question

How to restrict a field to take only 4 numeric characters as input and get's an alert in div

I wanted a text field to take only numbers as some control keys and number should be exactly four digit long. My code is as Follows:

<div id="main" role="main">
Input a 4-digit: <input type="text" class="validateYearTextBox" />
</div>
<div id="alert"></div>

function checkValidInput() {
$(".validateYearTextBox").keydown(function(event) {
if (!((event.keyCode == 46 ||
event.keyCode == 8 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 9) ||
$(this).val().length < 4 &&
((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105)))) {
// Stop the event
event.preventDefault();
return false;
}
});
}
$(document).ready(function() {

checkValidInput();
});


when I enter a 4 digit in the text box a alert should be appear in div as "valid"

this is the Fiddle

Answer

JSFiddle

Try following:

<div id="main" role="main">
    Input a 4-digit: <input type="text" class="validateYearTextBox" />
</div>
<div id="alert"></div>

<script>
function checkValidInput() {
    $(".validateYearTextBox").keydown(function(event) {       
        if (!((event.keyCode == 46 || 
            event.keyCode == 8  || 
            event.keyCode == 37 || 
            event.keyCode == 39 || 
            event.keyCode == 9) || 
            $(this).val().length < 4 &&
            ((event.keyCode >= 48 && event.keyCode <= 57) ||
            (event.keyCode >= 96 && event.keyCode <= 105)))) {
                        // Stop the event
                        event.preventDefault();
                        return false;                       
            }

            // count number of characters entered
            var cs = $('.validateYearTextBox').val().length;
            if(cs == 3)
            {
                $('#alert').html('valid'); 
            }
            else
            {
                $('#alert').html(''); 
            }
    });
}
$(document).ready(function() {

    checkValidInput();
});
</script>