ellandrd
asked on
validate field and fix NaN error
small shopping cart issue - users can enter the amount for the gift voucher. i validate the input but if the user enters an incorrect format i get NaN returned. How can I replace this with just 0.00?
function validatePrice()
{
function toPoundsAndPennys(n)
{
n = n.replace(/[^\d\.+-]/g,'');
if(/\d*\.\d*\./.test(n))
n = n.replace(/(\d*\.\d*)\./,'$1');
n = n.replace(/(\.\d{2})[\d.]*/g,'$1');
return n;
}
var price = toPoundsAndPennys(document.form.gift-vouchers-price.value);
if(isNaN(price))
{
price = 0.00;
}
document.form.gift-vouchers-price.value = price;
return;
}
Thsi statement will generate an error because of gift-vouchers-price, which is an illegal identifier
var price = toPoundsAndPennys(document .form.gift -vouchers- price.valu e);
Change this "gift-vouchers-price" to a valid javascript variable name.
Follow the following rules for javascript variable names
The first character must be a letter or an underscore (_). You can't use a number as the first character.
The rest of the variable name can include any letter, any number, or the underscore. You can't use any other characters, including spaces, symbols, and punctuation marks.
var price = toPoundsAndPennys(document
Change this "gift-vouchers-price" to a valid javascript variable name.
Follow the following rules for javascript variable names
The first character must be a letter or an underscore (_). You can't use a number as the first character.
The rest of the variable name can include any letter, any number, or the underscore. You can't use any other characters, including spaces, symbols, and punctuation marks.
ASKER
ok i correct my JS variable names and i still have the same issue.
heres my input field:
<input type="text" value="0.00" class="shop-fields" name="gift_vouchers_price" onkeyup="javascript:valida tePrice(); " onchange="this.value=(1 * this.value).toFixed(2);" onblur="this.value=(1 * this.value).toFixed(2);"
the rest of the code from above is unchanged...
heres my input field:
<input type="text" value="0.00" class="shop-fields" name="gift_vouchers_price"
the rest of the code from above is unchanged...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window