pretty simple issue here, this was working 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, i.e. 500\n";
$('.filter-price #price_from').val('From');
}
if (isNaN(price_to))
{
alert_message += "Price to must be a number, i.e. 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 web developer is giving me the error "price_from.toFixed is not a function" and my javascript is not working.
val returns a string; toFixed operates on numbers. Convert your string to a number like this:
Number(price_from).toFixed();
Note: You're checking whether the string contains a number using isNaN. This works because isNaN does an implicit number conversion before testing. To use any of the number methods, however, you'll need to do this same conversion explicitly, as shown above.
Don't confuse the JavaScript type of the object with what it represents. A string can contain a "number" in string form and still be just a string.
First of all 'isNaN' function does not REALLY check whether string represents number. For example isNaN('456a') returns true, but '456a' is not number at all. For this purpose you need other method of checking. I would suggest to use regular expressions.
Then you need to parse string for compareing numbers ( i.e. price_from < price_to ).
Here is the modificated code you may 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, i.e. 500\n";
$('.filter-price #price_from').val('From');
}
if (!isNumberRegExp.test(price_to))
{
alert_message += "Price to must be a number, i.e. 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);
}
});
Related
I'm trying to make binary to decimal converter.
I want to cut input to 8 digits and allow only 0s and 1s with JavaScript functions.
The first test works, but I did not succeed yet in detecting inputs that have some other character than only 0s and 1s. How can I achieve that?
This is what I've tried so far:
function bin2dec() {
var bin = document.getElementById("input").value;
if (bin.length > 8) {
document.getElementById("alert").innerHTML = "8 digits";
} else if (bin > 2) {
document.getElementById("alert").innerHTML = "Enter binary value";
} else {
document.getElementById("output").innerHTML = parseInt(bin, 2);
}
}
Testing bin > 2 is not helpful. You could use a regular expression to check if the input contains any characters other than 0 and 1.
if(/[^01]/.test(bin)){
//not binary
}
function bin2dec() {
var bin = document.getElementById("input").value;
document.getElementById("alert").innerHTML = "";
document.getElementById("output").innerHTML = "";
if (bin.length > 8) {
document.getElementById("alert").innerHTML = "8 digits";
} else if (/[^01]/.test(bin)) {
document.getElementById("alert").innerHTML = "Enter binary value";
} else {
document.getElementById("output").innerHTML = parseInt(bin, 2);
}
}
document.querySelector("button").addEventListener("click", ()=>bin2dec());
<input id="input">
<button>Convert</button>
<p id="output"></p>
<p id="alert" style="color: red;"></p>
I suppose your question is about fixing this part:
else if (bin > 2) {
This condition would be true for the following inputs (remember the input is a string):
"30000000"
"98765432"
which is indeed what you want,... but it would not be true for all of the following, while it should:
"20000000"
"12345678"
"09999999"
To check that a string only consists of "0" or "1" you could use a regular expression:
if (/[^01]/.test(bin)) {
This [^01] means "a character that is neither '0' nor '1'". The test method will return true when a match is found, i.e. if there is such a character in bin that is not "0" nor "1".
bin > 2 only checks if the input is a decimal number and if it's less than 2. I don't think that's what you want. Try something like this:
function bin2dec() {
var bin = document.getElementById("input").value,
num;
if (bin.length > 8) {
document.getElementById("alert").innerHTML = "8 digits";
} else if (isNaN(num = parseInt(bin, 2))) {
document.getElementById("alert").innerHTML = "Enter binary value";
} else {
document.getElementById("output").innerHTML = num;
}
}
Explanation: isNaN(num = parseInt(bin, 2)) assigns the parsed value to num and if it's invalid (NaN), says "Enter binary value", otherwise continues to the else statement.
When I run this code, console returns "Type Error: num.charAt is not a function". Why does this happen and how can I fix it.
function convertToRoman(num) {
var total = "";
if (num >= 1000){
total += "M";
}
if (num.charAt(1) >= 5){
total += "D";
}
return total;
}
convertToRoman(1500);
#String.charAt doesn't work on numbers. If you wish it to work properly, transform your num variable into a string, e.g.:
('' + num).charAt(1)
num.toString().charAt(1)
String(num).charAt(1)
("" + num).charAt(1)
Try to convert num to String.
The charAt() method returns the specified character from a string. Since your input is of type number it fails.
Hi can somebody tell me why the output to my function defaults to even when you insert over 17 numbers? It's probably super simple, please go easy on me!
function oddOrEven(number) {
var number = document.getElementById('number').value;
if(number % 2 != 0) {
document.getElementById('demo').innerHTML = "Odd";
}
else {
document.getElementById('demo').innerHTML = "Even";
}
if (number.length === 0) {
document.getElementById('demo').innerHTML = "Odd / Even";
}
}
You can simplify this whole thing. If you are always grabbing the input with id 'number' you don't need to pass a param, and then after a simple test you can inline the answer you want:
function oddOrEven(){
var val = document.getElementById('number').value;
var number = parseInt(val, 10);
// if it's not a valid number, you'll have NaN here which is falsy
if (number) {
document.getElementById('demo').innerHTML = (number % 2) ? "Even" : "Odd";
}
}
All that said, I just caught that you're talking about 17 digits (thanks to #JJJ's comment) rather than using the function more than once. The problem in this case is that JS integers have a size limit. If you parse anything larger it returns a number you're not going to expect. There are a lot of discussion of general handling of very large numbers here: http://2ality.com/2012/07/large-integers.html, but for your modulus problem you could take the last digit and check if that's odd or even like so:
function oddOrEven(){
var val = document.getElementById('number').value;
var number = parseInt(val, 10);
// if it's not a valid number, you'll have NaN here which is falsy
if (number) {
var lastDigit = val[val.length-1];
document.getElementById('demo').innerHTML = (parseInt(lastDigit, 10) % 2) ? "Even" : "Odd";
}
}
I have a function to sum values with same ID; jsFiddle. This works, but not if is a decimal value, like a money value. (10,05 + 1.005,10, example)
$('#button-cart').on('click', function() {
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseInt($(this).val()));
sum += parseInt($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});
How can we fix it?
Use parseFloat instead of parseInt when dealing with decimal values.
parseInt() function parses a string argument and returns an integer or NaN. If not NaN, the returned value will be the integer representation of the string passed in.
parseFloat() function parses a string argument and returns a floating point number or Nan(If the string expression cannot be converted to a numerical value).
Here is a working sample.
You must use parseFloat:
just replace your current code with the following one:
$('#button-cart').on('click', function() {
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseFloat($(this).val()));
sum += parseFloat($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});
This gonna help you :)
I've updated your script a bit (js lines 10-16)
https://jsfiddle.net/La18Lcns/10/
If you want to use number taplate such as
1.142,32
23.456,5
1.500
First you need to conver it to float format
1142.32
23456.5
1500
Than you use parseFloat() instead ParseInt()
$('#button-cart').on('click', function()
{
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseFloat($(this).val()));
sum += parseFloat($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});
so, my problem here is that my code seems to be recognizing that 100 is < 2000, but its not recognizing that 200 < 1000
heres my code (i also use jquery as a framework FYI)
$('.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))
{
alert_message += "Price from must be a number, i.e. 500\n";
$('.filter-price #price_from').val('From');
}
if (isNaN(price_to))
{
alert_message += "Price to must be a number, i.e. 500\n";
$('.filter-price #price_to').val('To');
}
if (!isNaN(price_from) && !isNaN(price_to) && (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);
}
});
i've tried using parseInt() on the vars which fixes nothing.
Sorry, but you really need to do this way:
var price_from = parseInt($('.filter-price #price_from').val(), 10);
var price_to = parseInt($('.filter-price #price_to').val(), 10);
Look the result on chrome console:
'200' >= '1000'
true
200 >= 1000
false
And if you don't want to limit the numbers to int, replace parseInt(val, 10) to parseFloat(val)
parseInt works for me. Not sure what was incorrect for you.
http://jsfiddle.net/98Bzn/1
var price_from = parseInt($('.filter-price #price_from').val());
var price_to = parseInt($('.filter-price #price_to').val());
Where have you tried using parseInt()? It seems to me that it's interpreting your values as strings rather than numbers, so you need to coerce them into the correct data type.
I would do this:
function convertCurrencyToNumber(value) {
return Number(value.replace(/[^0-9\.]+/g,""));
}
...
var price_from = convertCurrencyToNumber($('.filter-price #price_from').val());
var price_to = convertCurrencyToNumber($('.filter-price #price_to').val());
It appears you're using currency, so the above will convert to a decimal for database storage or whatever else you're doing.