gripen fighter gripen fighter - 1 year ago 68
HTML Question

Allow html input box to only enter one full number and exactly decimal .5

I'm making web application that requires users to enter number with one decimal place. I restrict users from entering other characters that numbers from using this javascript code


<input type="number" name='days' class="w3-input w3-padding-tiny" id="cntday" onkeypress="return isNumberKey(event)" placeholder="Enter days"/>


function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31 &&
(charCode < 48 || charCode > 57))
return false;
return true;

but this function only prevent users from entering characters other than numbers.
I need to prevent users from entering more than one decimal places as well as entered decimal should be .5

it's like this

  • if user enter 5.55 it should replace with 5.5 OR prevent user to input additional decimal

  • and if user enter 5.2 OR any decimal it should be replace with 5.5 in other words users should only able to enter number with decimal .5

how can I achieve this with my current onkeypress function ?

This is NOT a duplicate of the other question. Stop flagging this

Answer Source

Use this

$('#cntday').keyup(function() {
    if(this.value %1 != 0.5){
        this.value = this.value - this.value%1 + 0.5;

The condition checks whether a decimal has been entered or not and as soon as a decimal is entered and a number is entered it changes it to .5 It fulfills both the requirements you mentioned. Check it here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download