Price_from.toFixed () is not a function

a pretty simple problem here, it worked before, but not anymore.

heres my code:

$('.filter-price').submit(function(e) { var alert_message = ''; var price_from = $('.filter-price #price_from').val(); var price_to = $('.filter-price #price_to').val(); if (isNaN(price_from) || isNaN(price_to)) { if (isNaN(price_from)) { alert_message += "Price from must be a number, ie 500\n"; $('.filter-price #price_from').val('From'); } if (isNaN(price_to)) { alert_message += "Price to must be a number, ie 500\n"; $('.filter-price #price_to').val('To'); } } else { price_from = price_from.toFixed(); price_to = price_to.toFixed(); if (price_from >= price_to) { alert_message += "Price from must be less than price to\n"; $('.filter-price #price_from').val('From'); $('.filter-price #price_to').val('To'); } } if (alert_message != '') { e.preventDefault(); alert(alert_message); } }); 

now the web developer gives me the error "price_from.toFixed is not a function" and my javascript is not working.

+4
source share
2 answers

First of all, the isNaN function does NOT REALLY check if a string is a number. For example, isNaN ('456a') returns true, but '456a' is not a number. For this you need a different verification method. I would suggest using regular expressions.

Then you need to parse the string to compare numbers (i.e. price_from <price_to).

Here is a modified code that you can assume:

 $('.filter-price').submit(function(e) { var alert_message = ''; var price_from = $('.filter-price #price_from').val(); var price_to = $('.filter-price #price_to').val(); var isNumberRegExp = new RegExp(/^[-+]?[0-9]+(\.[0-9]+)*$/); if (!isNumberRegExp.test(price_from) || !isNumberRegExp.test(price_to)) { if (!isNumberRegExp.test(price_from)) { alert_message += "Price from must be a number, ie 500\n"; $('.filter-price #price_from').val('From'); } if (!isNumberRegExp.test(price_to)) { alert_message += "Price to must be a number, ie 500\n"; $('.filter-price #price_to').val('To'); } } else { price_from = parseFloat(price_from); price_to = parseFloat(price_to); if (price_from >= price_to) { alert_message += "Price from must be less than price to\n"; $('.filter-price #price_from').val('From'); $('.filter-price #price_to').val('To'); } } if (alert_message != '') { e.preventDefault(); alert(alert_message); } }); 
+6
source

val returns a string; toFixed works with numbers. Convert the string to a number like this:

 Number(price_from).toFixed(); 

Note. . You check if a string contains a number using isNaN . This works because isNaN performs an implicit number conversion before testing. However, to use any of the number methods, you will need to do the same conversion explicitly, as shown above.

Do not confuse the type of JavaScript object with what it represents. A string can contain a "number" in string form and still be just a string.

+20
source

Source: https://habr.com/ru/post/1387983/


All Articles