yaksushi - 9 months ago 43

Javascript Question

I'm new to javascript and I have input boxes that must not allow a zero value or non-numbers. I originaly tried to create a regular expression but I couldn't seem to get any of them to work correctly. I then came up with the following solution but it seems to only work some of the time. I think my if statements are jacked up. Any help with the code as far as making it better would be greatly appreciated.

HTML:

`<input name="payrate" id="payrate"></td>`

<input name="hours" id="hours" value="0" onclick="dollars()" onchange="dollars()"></td>

Javascript:

`function dollars(){`

var rate = 0;

rate= document.getElementById("payrate").value;

var hours= document.getElementById("hours").value;

if(!isNaN(hours)){

// !isNan - not a Number

// !rate == 0 - value not equal to 0

if (!isNaN(rate) && !rate == 0) {

//round value of payrate to 2 decimal places

var adjrate = Math.round(rate*100)/100;

document.getElementById("payrate").value="";

document.getElementById("payrate").value= adjrate;

for (i=0; i<6; i++){

document.paycheck['tax'+i].disabled = false;

}

}else{

alert("You entered an invalid rate.\n"+

"Please enter your hourly pay.\n"+

"Example: 8.87 value entered: " + rate);

rate = "";

disableRadio();

resetForm();

}

}else{

alert("You entered invalid or empty hours.\n"+

"Please enter the number of hours worked.\n"+ hours);

hours = "";

disableRadio();

resetForm();

}

}

Answer Source

There is no need to check two times for isNaN. Try to simplify the conditions like this:

```
function dollars(){
var rate = 0;
rate= document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!isNaN(hours)){
// !isNan - not a Number
// !rate == 0 - value not equal to 0
if (rate > 0) {
//round value of payrate to 2 decimal places
var adjrate = Math.round(rate*100)/100;
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
}else{
alert("You entered an invalid rate.\n"+
"Please enter your hourly pay.\n"+
"Example: 8.87 value entered: " + rate);
rate = "";
disableRadio();
resetForm();
}
}else{
alert("You entered invalid or empty hours.\n"+
"Please enter the number of hours worked.\n"+ hours);
hours = "";
disableRadio();
resetForm();
}
}
```