I need to write a code in javascript to accept numbers in a textbox in a certain interval (that part is done, between 0 and 16) and now I need it to accept numbers such as 1.5, 1.75, 9.75, 0, 3.25, etc. All numbers with their quarts. All other numbers should be rejected.
Accepted = textbox background is green. Rejected = textbox background is red.
<script type="text/javascript">
function readNumbersAndReturnsArray() { //to fix
var tabNombre = new Array()
for (var i = 0; i < 7; i++){
var strNombre = document.getElementById('tbNbHrs' + i).value
if (isAnEmptyString(strNombre) || !containsNumbersOnly(strNombre))
{
var strMiseEnForme = 'sNotNumber'
}
else if (!estDansIntervalle(strNombre,'0','16'))
{
var strMiseEnForme = 'sOutOfLimit'
}
else if(-----------) //this is the part where I should accept numbers and their quarts only (0, 0.25, 0.5, 0.75, 1, 1.25, etc.)
{
var strMiseEnForme = 'sNotQuart'
}
else
{
var strMiseEnForme = 'sValid'
strNombre = Number(strNombre)
tabNombre.push(strNombre)
}
document.getElementById('tbNbHrs' + i).className = strMiseEnForme
}
return tabNombre
Note: All other functions are already working and coded in a js library.
The solution is to use the modulus operator. The modulus operator returns the remainder of a division operation.
The modulus operator is represented as a % in javascript and many other languages.
For example:
All the numbers you list as "valid" (1, 1.25, 3.75 etc.) are divisible by 0.25. Simply use the modulus operator and see if you get a remainder of 0. If so then the number is divisible by 0.25 and is valid.
Your if statement should be:
if(strNombre % 0.25 == 0){
// VALID: Number is 1.75, 2, 2.25 etc.
}else{
// INVALID
}