So here's my code:
var score1 = $(this).attr('data-score1');
var score2 = $(this).attr('data-score2');
if (score1 < score2) {
// do some
}
if (score2 > score1) {
// do something else
}
Now, this works fine as long as both variables are either both < or both > 100, yet whenever either of those variable is larger than 100 while the other is not the wrong if statement gets triggered. What the hell could be going on here?
Thanks for any advice!
Use parseInt()
The attributes will throw up strings.. So when you try to compare them... You are actually comparing
"100" > "90" and not 100 > 90 .. Using parseInt() with a radix should solve your problem..
var score1 = parseInt( $(this).attr('data-score1') , 10);
var score2 = parseInt( $(this).attr('data-score2') , 10);
if (score1 < score2) {
// do some
}
else if (score2 > score1) {
// do something else
}
As #naveen suggested you could do this as well
var score1 = +$(this).attr('data-score1');
var score2 = +$(this).attr('data-score2');
You're comparing the values as strings. The string "90" begins with 9, which has an ascii code that is greater than that of 1.
You can convert it to a number by using parseInt
parseInt(score1, 10)
Related
I have the folowing code:
var price1 = (length1 * width1) * priceSM / 10000;
if (price1 < 10) {
alert("Size too small");
return;
}
document.getElementById('result1').innerHTML = Math.round(price1);
What I need to do:
If price 1 < 10 alert AND then price1 = 10, but if price1 = 0, or bigger than 10, that's fine.
length1 and width1 are INPUTS
Please help, I'm at very beginning with javascript.
I don't know if I understand well what you want.
Try this ?
var price1=(length1*width1)*priceSM/10000;
if(price1 < 10 && price1 != 0){
alert("Size too small");
price1 = 10;
return;
}
document.getElementById('result1').innerHTML=Math.round(price1);
If you want to update your element "result1" with price1 when < 10 then just remove "return;"
If it isn't what you want, please tell us and post all function's code please.
To avoid the alert when the price is zero, add that in the condition with the && operator:
price1 > 0 && price1 < 10
To set the price to 10 in that case, add this to the if block:
price1 = 10
To really show the modified price (10), you should remove the return statement from that if block. That way the code will continue to execute the last statement.
Finally, not really a problem, but it is better to use the textContent property instead of the innerHTML property when you intend to assign something that is plain text and not HTML.
So your code then becomes:
var price1 = (length1 * width1) * priceSM / 10000;
if (price1 > 0 && price1 < 10) {
price1 = 10
alert("Size too small");
}
document.getElementById('result1').textContent = Math.round(price1);
Using .value property you are able to set the value.
document.getElementById("myText").value = "Hello World...";
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'm trying to validate a decimal number between 0.0 to 0.999 or .0 to .999.
I'm trying the below,
$('#num').on("keyup", function () {
var value = $(this).val();
var regex_cell = /0(\.\[0-9]{3})?/;
if (!value.match(regex_cell)) {
this.value = this.value.replace(this.value.slice(-1), "");
}
});
Instead of using regex you could convert to float and validate it.
var s = "0.999";
var n = Number.parseFloat(s);
if (n >= 0 && n <= 0.999) // 3 decimal positions only? s.length <= 4
{
// valid
}
The regex is
var regex_cell = /0(\.[0-9]{1,3})?/
var regex_cell = /0?(\.[0-9]{1,3})?/
0 is optional. Still, 0. would fail. Blank would fail. Best way is to do the evaluation with floats probably (use 'Number.parseFloat'). This is not a good job for a regex
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.
I'm trying to show numbers in labels. If the number > 1000 the format should look like
1.000 or 1,000
I tried with toFixed but it is not the solution, also toPrecision but it gave me a number like 1,2e+
I tried with
number/1000
but when the number ends up with a 0, it disappears from the result, so how can i do this??
I whipped up the following function. It will add a comma after 3 digits. Works on whole numbers.
function formatNumber(num)
{
var formattedNumber = "";
var numString = num.toString();
var numCount = 0;
for (var index = numString.length - 1; index >= 0; index--)
{
if (numCount % 3 == 0
&& numString[index] != '-'
&& formattedNumber)
{
formattedNumber = ',' + formattedNumber;
}
formattedNumber = numString[index] + formattedNumber;
numCount++;
}
return formattedNumber;
}
You would have to write your own function. Something like this:
http://www.mredkj.com/javascript/nfbasic.html
EDIT: Found the original code