rafalefighter
rafalefighter

Reputation: 734

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

html

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

javascript

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

how can I achieve this with my current onkeypress function ?

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

Upvotes: 0

Views: 682

Answers (2)

Netham
Netham

Reputation: 1178

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 https://jsfiddle.net/xn0koawx/

Upvotes: 1

Shady Alset
Shady Alset

Reputation: 5714

You can do it by split the number into two parts:

Part 1 for natural number.

Part 2 for decimal number.

then you can replace any entered decimal number to .5

Something like this:

$('input').keyup(function() {
var value = this.value;
var pos = value.indexOf(".");
var result;
if (pos !== -1) {
    var part1 = value.substr(0, pos);
    var part2 = value.substr(pos);
    result = part1 + part2.replace(part2,".5")
    $('input').val(result);
}
});

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode != 46 && charCode > 31 &&
        (charCode < 48 || charCode > 57))
        return false;
        return true;
}  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name='days' class="w3-input w3-padding-tiny" id="cntday"  onkeypress="return isNumberKey(event)" placeholder="Enter days"/>

Upvotes: 1

Related Questions