jsFiddle: http://jsfiddle.net/Mw4j2/6/
Trying to change attributes to a selector if the seconds count is 10 or under.
I'm using
var returnSecondsNumber = $('.countdownSecond > .countSeconds > .position:first-child > .digit').text() + $('.countdownSecond > .countSeconds > .position:nth-child(2) > .digit').text();
To grab the numbers from both spans and returns it as 16/15/14/etc.
Now I need do something if this numeric is under 10.
e.g.
if (returnsSecondsNumber <= 10)
{ $(this).addClass('urgent');
}, else { //do something
}
I've tried taking a look at parseInt with no success. Any help would be much appreciated!
Thanks.
Two things:
First, you need to move the code that constructs "returnSecondsNumber" into the callback function(s) of whichever timers you want to monitor.
Second, just use parseInt():
var numericVal = parseInt(returnsSecondsNumber, 10);
if (!isNaN(numericVal) && numericVal < 10) {
// do whatever
}
Try
if(!isNaN(parseInt(returnsSecondsNumber )) && returnsSecondsNumber < 11)
//Do stuff...
One thing to keep in mind is that if the value of returnsSecondNumber is a starts with a number that will be returned instead of NaN
Related
Can someone please help implement something in my javascript project? #http://codepen.io/urketadic/pen/YpLgBX
I want number to turn red if its wrong and not in sequence with pi. Its really difficult for me to keep count and compare with everything.
I've tried a lot of this and at the end I've come up with this code:
var count = 0;
// color the mistake right away
$("#inputsm").keyup(function(event) {
var pressed = event.key;
answer = $("#inputsm").val();
pisub = pi.substr(input,answer.length)
if (pressed!=="Backspace"&&pressed!=="Delete") count++;
else count--;
console.log(count);
});
I'm just confused, i don't know how i can do this. Also does text area even allow numbers to turn red? I've tried adding jquery css as well but it doesn't work. Can someone write it in their own codepen and post a link?
Take a look at this fiddle: https://jsfiddle.net/ebv5n64j/2/
I've put together something that does basically what you are trying to do. You can modify it from there but that is the basic concept. I designed mine to not let the user continue until they get it right, but you could easily change that.
This is a snippet, but jsfiddle has the complete working version:
// If it's a delete command
if(code === 8){
if(!$("#wrong").length > 0)
inputCount = (inputCount === 0 ? 0 : --inputCount);
$("#pi span").last().remove();
console.log(inputCount);
} else if (code >= 48 && code <= 57) {
var inputNumber = code - 48;
var numSpan;
$("#wrong").remove();
numSpan = $("<span>"); // make a new one
// Append the number
numSpan.text(inputNumber);
numSpan.removeClass("incorrect");
if(String(inputNumber) === piDigits[inputCount]){
numSpan.addClass("correct");
inputCount++;
} else {
numSpan.attr("id", "wrong");
}
$("#pi").append(numSpan);
placeCaretAtEnd(this);
}
So I looked at your pen and thought that you were somewhat over-complicating the solution. I think a better way would be to compare the string of the input textarea with the substring of pi. Anyways, here's the fixed code and I've linked to the pen with the working version.
By the way, you mention in the description that if they want to start at the number 4 in 3.14 they should type in 1 (for index 1), but you take their input and subtract it by 1, so it essentially starts them off at 1 instead of 4, if they typed in 1.
$("#inputsm").keyup(function() {
var thisLength = parseInt(input) + $(this).val().length - 1;
if($(this).val().trim() === pi.substring(parseInt(input), thisLength)) {
console.log("good so far!");
$(this).removeAttr('style');
} else {
console.log("ahhh no good!");
$(this).css('background', 'red');
}
});
http://codepen.io/msafi/pen/dOKogK/
Using numeric keypad I have added a .switch handler which when clicked will bring the value back to '0' (test purpose only)
If the value is +32 and the button is pressed I would like it to change to -32, vice versa.
so far I have only gotten it to return to 0, i was thinking then deleting or adding the val again, even tried -- $('#myInput').val());
$('.switch').click(function () {
if (!isNaN($('#myInput').val()) && $('#myInput').val().length > 0) {
$('#myInput').val(parseInt($('#myInput').val()) - $('#myInput').val());
}
if (!isNaN($('#myInput').val()) && $('#myInput').val().length < 0) {
$('#myInput').val(parseInt($('#myInput').val()) + $('#myInput').val());
}
});
If all you're trying to do is switch back and forth between a positive/negative number you can make your code much simpler and lose all the if conditions:
$('.switch').click(function () {
var $input = $('#myInput');
$input.val() != "" && !isNaN($input.val()) && $input.val(-$input.val());
});
This is the equivalent of multiplying the number by -1, which will have the same effect.
Example fiddle
$('#myInput').val().length < 0
when will a length of a string be less than zero?
parseInt($('#myInput').val()) + $('#myInput').val()
this doesn't actually do numeric addition, if th value is the string 1 then it will be like doing 1+"1" which will return 11
I think what you're looking for is :
$('.switch').click(function () {
var val = parseInt($('#myInput').val());
$('#myInput').val(-val);
});
see here
I have a javascript code that compares two values:
} else if (!(parseInt($('#form_value').val()) >= 1)){
alert("Error: You didn't pick a number!");
form_value in this case is 001, and I would like to compare it to the one, but it doesn't seem to work. I have tried using parseInt but it didn't work either. Any solutions?
Try:
if (!(Number(parseInt($('#form_value').val(),10)) >= 1)){
EDIT: try this shortened version:
if ( parseInt($('#form_value').val(),10) < 1){
Well, Number("001"); returns 1 and Number("000"); returns 0
based on your comment above
"I'm trying to display an error if the value is less than 1, the
lowest value a user can submit is 000 (which is loaded by default), if
you pick something, it becomes 001."
If the lowest possible value is 0 then just test for 0...
var thing = Number($('#form_Value').val());
if (isNaN(thing) || thing === 0) {
alert('an error message')'
}
May be you should change the condition to if ( +( $('#form_value').val() ) < 1 ) or just if (!+$('#form_value').val()).
I have the following variable:
pageID = 7
I'd like to increment this number on a link:
$('#arrowRight').attr('href', 'page.html?='+pageID);
So this outputs 7, I'd like to append the link to say 8. But if I add +1:
$('#arrowRight').attr('href', 'page.html?='+pageID+1);
I get the following output: 1.html?=71 instead of 8.
How can I increment this number to be pageID+1?
Try this:
parseInt(pageID, 10) + 1
Accordint to your code:
$('#arrowRight').attr('href', 'page.html?='+ (parseInt(pageID, 10) + 1));
+ happens to be valid operator for both strings and numbers that gives different results when both arguments are numeric and when at least one is not. One of possible workarounds is to use operator that only have numeric context but gives same mathematical result, like -. some_var - -1 will always be same as adding 1 to some_var's numeric value, no matter if it is string or not.
$('#arrowRight').attr('href', 'page.html?='+ (pageID - -1));
All these solutions assume that your number you want to add 1 to is within the machine precision for an integer. So if you have a large enough number within that string when you add 1 to it won't change the number.
For Example:
parseInt('800000000000000000', 10) + 1 = 800000000000000000
So I wrote a quick solution to the problem
function addOne(s) {
let newNumber = '';
let continueAdding = true;
for (let i = s.length - 1; i>= 0; i--) {
if (continueAdding) {
let num = parseInt(s[i], 10) + 1;
if (num < 10) {
newNumber += num;
continueAdding = false;
} else {
newNumber += '0';
}
} else {
newNumber +=s[i];
}
}
return newNumber.split("").reverse().join("");
}
Now, using the same example above
addOne('800000000000000000') + 1 = '800000000000000001'
Note that it must stay as a string or you will lose that 1 at the end.
It needs to be a integer, not a string. Try this:
pageID = parseInt(pageID)+1;
Then you can do
$('#arrowRight').attr('href', 'page.html?='+pageID);
Simply, $('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The parentheses makes the calculation done first before string concatenation.
let pageId = '7'
pageId++
console.log(pageId)
Nowadays, you just need to pageID++.
Just change your order of operations by wrapping your addition in parentheses; if pageID is already a number, parseInt() isn't necessary:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
Demo
As long as your pageID is numeric, this should be sufficient:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The problem you were seeing is that JavaScript normally executes in left-to-right order, so the string on the left causes the + to be seen as a concatenator, so it adds the 7 to the string, and then adds 1 to the string including 7.
What's the best way to detect if a number, is between two other numbers? Is there already a function to do this in the Math object?
There is no specific function, but you can do it like this:
lowNumber < yourNumber && yourNumber < highNumber
Though the code solution is fairly obvious, if you're going to use it a lot, you may want to implement it on Number.prototype for convenience:
Number.prototype.inRange = function( a,b ) {
var n = +this;
return ( n > a && n < b );
};
So you'd use it like this:
(5).inRange( 3, 7 ); // true
Example: http://jsfiddle.net/dTHQ3/
Um if it is greater than one and less than the other.
var num1 = 3;
var num2 = 5;
var x = 4;
var isBetween = (num1 < x && num2 > x);
if ( yournumber < highNumber && yournumber > lowNumber ){
// do something
} else {
// do something else
}
The only optimized way to do this is to guess which is more likely: Is the number your checking more likely to be lower than the lower bound, or is it more likely to be higher than the upper bound?
With this in mind, you can take advantage of short circuiting by placing the more likely failure check first (if it fails that, it won't test the less likely criteria). This is the only way to optimize it.
Even this will save you the smallest amount of time that is most likely not going to be noticed. Perhaps if you were making this check millions of times, you might save a fraction of a second over the alternative.