The problem is in the keydown triggered before the value update. So if you enter '2'. The value will return '' And Number('') is 0 so it always go to else
Just remove the keydown event only use keyup
$(function() {
$('#installment').on("keyup", check);
function check() {
var inst = Number($("#installment").val());
console.log(inst)
if (inst === 2 || inst === 4 || inst === 6 || inst === 12) {
return true;
} else {
$("#installment").val('');
alert("you can not set wrong value");
return false;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td>Number of Installment</td>
<td><input type="text" name="installment" id="installment"></td>
</tr>
As @Radu Diță mentioned in the comment that 12 can never be valid if 1 is not so to fix that you can use String.prototype.startsWith()
$(function() {
$('#installment').on("keyup", check);
function check() {
var inst = Number($("#installment").val());
console.log(inst)
if (inst === 2 || inst === 4 || inst === 6 || '12'.startsWith(String(inst))) {
return true;
} else {
$("#installment").val('');
alert("you can not set wrong value");
return false;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td>Number of Installment</td>
<td><input type="text" name="installment" id="installment"></td>
</tr>
Number()around it