I have a basic counter that counts up within an input field. this works exactly how I want it to. The problem I am facing is that I can only set the target number via the input value. i want to be able to set this via a js variable, ignoring the html input value
DEMO http://jsfiddle.net/vyN6V/238/
Current jQuery
var number = 827;
function count(Item){
var current = parseInt(Item.val());
Item.val(current +=5);
if(current < number){
setTimeout(function(){count(Item)}, 0.1);
}
}
count($(".input"));
Desired jQuery (doesn't work)
var number = 827;
var aValue = 500;
function count(Item){
var current = aValue;
Item.val(current +=5);
if(current < number){
setTimeout(function(){count(Item)}, 0.1);
}
}
count($(".input"));
Should work, you just forgot to add 5 to aValue:
var current = aValue;
aValue+=5;
Your current is inside your function, it works if you simply use aValue:
Item.val(aValue += 5);
Fiddle
this would solve the problem: http://jsfiddle.net/Jg6LN/1/
var number = 827;
var aValue = 500;
function count(Item, value){
var current = value || parseInt(Item.val());
Item.val(current +=5);
if(current < number){
setTimeout(function(){count(Item)}, 0.1);
}
}
count($(".input"), aValue);
What about this?
var aValue = 500;
var number = 827;
function count(Item) {
var current = parseInt(Item.val()) || aValue;
Item.val(current + 5);
if (Item.val() < number) {
setTimeout(function () {
count(Item)
}, 0.1);
}
}
count($(".input"));
http://jsfiddle.net/vyN6V/242/
Related
The goal of this "counter" is to see how many different words are inside the "ToCount"string. To do that it makes ToCount an array and then iterates over the elements, checking if they already are there and if not, adding them there.
The ToCountArr2 remains empty after the loop and a length of 0 is being displayed. Why does that happen and what can I do about it?
I ran a debugger and saw that no elements are added to the second list, as if nothing appenned inside the "if" control if the i-th element of the first array already is inside the second array.
function counter(){
var ToCount = document.getElementById("demo").value; //the contents of a textbox
var ToCountArr1 = ToCount.split(" ");
var ToCountArr2 = new Array;
var i = 0;
var lengthToCountArr1 = ToCountArr1.length;
var wordToPush;
while (i < lengthToCountArr1){
if(ToCountArr2.includes(ToCountArr1[i] === false)) {
wordToPush = ToCountArr1[i];
ToCountArr2.push(wordToPush);
}
i = i + 1;
}
alert(ToCountArr2.length);
}
The issue is with this line if(ToCountArr2.includes(ToCountArr1[i] === false)). Here the braces need to be after ToCountArr1[i], where as this line ToCountArr1[i] === false) is checking whether that value in ToCountArr1 is true or false.
This line
if(ToCountArr2.includes(ToCountArr1[i] === false)) will be evaluated as
if(ToCountArr2.includes(true/false))
depending on result of ToCountArr1[i] === false)
function counter() {
var ToCount = document.getElementById("demo").value; //the contents of a textbox
var ToCountArr1 = ToCount.split(" ");
var ToCountArr2 = new Array;
var i = 0;
var lengthToCountArr1 = ToCountArr1.length;
var wordToPush;
while (i < lengthToCountArr1) {
if (ToCountArr2.includes(ToCountArr1[i]) === false) {
wordToPush = ToCountArr1[i];
ToCountArr2.push(wordToPush);
}
i = i + 1;
}
console.log(ToCountArr2.length);
}
counter()
<input type='text' id='demo' value='Test Values'>
You can minimize if (ToCountArr2.includes(ToCountArr1[i]) === false) { by replacing it with
if (!ToCountArr2.includes(ToCountArr1[i])) {
Your wordcount function should use a parameter so you can pass a string in. This means you can use the wordcount function on an any string, not just the "demo" element. Also, this is a good time to learn about Map -
const wordcount = (str = "") =>
{ const result =
new Map
for (const s of str.split(/ /))
if (s === "")
continue
else if (result.has(s))
result.set(s, result.get(s) + 1)
else
result.set(s, 1)
return Array.from(result.entries())
}
const prettyPrint = (value) =>
console.log(JSON.stringify(value))
<!-- pass this.value as the string for wordcount
-- wordcount returns a value that we could use elsewhere
-- prettyPrint displays the value to the console
-->
<input onkeyup="prettyPrint(wordcount(this.value))">
Run the code snippet and copy/paste the following line into the field -
this is the captain speaking. is this the commander?
You will see this output -
[["this",2],["is",2],["the",2],["captain",1],["speaking.",1],["commander?",1]]
Here is an working example. I think it will help you right way. Here I use indexOf to check the value exist on a array.
function counter(){
var ToCount = "I am string just for text.";//document.getElementById("demo").value; //the contents of a textbox
var ToCountArr1 = ToCount.split(" ");
var ToCountArr2 = new Array;
var i = 0;
var lengthToCountArr1 = ToCountArr1.length;
var wordToPush;
while (i < lengthToCountArr1){
if( ToCountArr2.indexOf(ToCountArr1[i]) == -1 ) {
wordToPush = ToCountArr1[i];
ToCountArr2.push(wordToPush);
}
i = i + 1;
}
alert(ToCountArr2.length);
}
counter();
I have function that calculates difference between current and previous rows
Here it is
function distanceDifference() {
var rowsDistance = $('#tbody tr');
for (j = 1; j < rowsDistance.length; j++) {
// Get the rows
var previousDistanceRow = rowsDistance.eq(j - 1);
var currentDistanceRow = rowsDistance.eq(j);
var previousDistance = previousDistanceRow.find('td').eq(5).text();
var currentDistance = currentDistanceRow.find('td').eq(5).text();
//alert(previousDistance);
var difference = currentDistance - previousDistance;
//alert(difference);
currentDistanceRow.find('td').eq(6).text(difference);
}
}
It works well for all values
But I have column
<td id="dataType">#data.Datatype</td>
Value of it can be 0,1,2
I need to calculate difference only if it ===2
I try to do it like this
function distanceDifference() {
var rowsDistance = $('#tbody tr');
for (j = 1; j < rowsDistance.length; j++) {
var value = $('#dataType').text();
if (value === 2) {
// Get the rows
var previousDistanceRow = rowsDistance.eq(j - 1);
var currentDistanceRow = rowsDistance.eq(j);
var previousDistance = previousDistanceRow.find('td').eq(5).text();
var currentDistance = currentDistanceRow.find('td').eq(5).text();
//alert(previousDistance);
var difference = currentDistance - previousDistance;
//alert(difference);
currentDistanceRow.find('td').eq(6).text(difference);
}
}
}
but it not works. How I need to write code correctly?
Use if (value == 2) instead of if (value === 2).
Because equality operator === compares also the operands data types.
But the data type for the value '2' is string and you comparing with integer 2
Operator == will compare only value 2 == 2, without comparing the operands data types!
Even though a non-strict comparison would work it is - in my opinion - better practice to validate and convert user input to a specific data type.
So if you expect the users input to be an integer, use this
var value = parseInt( $('#dataType').text(), 10 );
If you expect it to be a number with a floating point, use this instead:
var value = parseFloat( $('#dataType').text() )
Then you can use a strict comparison like you already did.
But always validate if the user input has the right format.
So trouble was in that I get only first value from column
Here is valid code
function distanceDifference() {
var rowsDistance = $('#tbody tr');
for (j = 1; j < rowsDistance.length; j++) {
//var value = parseInt($('.dataType ').html());
var test = $('.dataType');
if (parseInt($(test[j]).html()) === 2) {
// Get the rows
var previousDistanceRow = rowsDistance.eq(j - 1);
var currentDistanceRow = rowsDistance.eq(j);
var previousDistance = previousDistanceRow.find('td').eq(5).text();
var currentDistance = currentDistanceRow.find('td').eq(5).text();
var difference = currentDistance - previousDistance;
currentDistanceRow.find('td').eq(6).text(difference);
}
}
}
So I need to take a date and convert it into one single number by adding up each digit, and when the sum exceeds 10, I need to add up the two digits. For the code below, I have 12/5/2000, which is 12+5+2000 = 2017. So 2+0+1+7 = 10 & 1+0 = 1. I get it down to one number and it works in Firebug (output of 1). However, it is not working in a coding test environment I am trying to use, so I suspect something is wrong. I know the code below is sloppy, so any ideas or help reformatting the code would be helpful! (Note: I am thinking it has to be a function embedded in a function, but haven't been able to get it to work yet.)
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
solution("2000, December 5");
You can just use a recursive function call
function numReduce(numArr){
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend","Reducing: "+numArr.join(","));
//Using the array's reduce method to add up each number
var total = numArr.reduce(function(a,b){return (+a)+(+b);});
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend",": Total: "+total+"<br>");
if(total >= 10){
//Recursive call to numReduce if needed,
//convert the number to a string and then split so
//we will have an array of numbers
return numReduce((""+total).split(""));
}
return total;
}
function reduceDate(dateStr){
var arrayDate = new Date(dateStr);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
return numReduce([d,m+1,y]);
}
alert( reduceDate("2000, December 5") );
<div id="log"></div>
If this is your final code your function is not outputting anything. Try this:
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
alert(solution("2000, December 5"));
It will alert the result in a dialog.
I need to convert an input field into a number. So if the input field is empty, or contains letters, the number would be 0.
This doesn't work:
var trade_gold = document.getElementById('trade_gold').value;
if (trade_gold < 1) {
I've tried parseInt on it too, can't seem to work it. Any advice?
var val = document.getElementById('trade_gold').value,
trade_gold = parseFloat(val) || 0;
var value = document.getElementById('trade_gold').value;
value = parseInt(value, 10);
// parseInt will return NaN if the conversion failed
if (isNaN(value)) {
value = 0;
}
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt
var trade_gold = 0;
try{
trade_gold = parseInt(document.getElementById('trade_gold').value, 10);
}catch(e){}
this will checks whether the it's a number or not, and change the value to 0 if it's not.
var trade_gold = document.getElementById('trade_gold').value;
if (trade_gold.search(/[^0-9]/)>=0)
{
// not a number
trade_gold = 0;
}
I'm trying to do a simple JS loop where I initialize a variable with a value outside the loop, but for some reason its not working.
Basically, I'd like to have total_money equals to 20 in my example, but it keeps returning money
var total = 0;
var money = 20;
var ticker = ['money'];
for (tick in ticker) {
total_money = ticker[tick];
}
console.log(total_money);
Remove the single-quotes '...' from your array called ticker:
var total = 0;
var money = 20;
var ticker = [money]; // <-- Remove the single-quotes
for (tick in ticker) {
total_money = ticker[tick];
}
console.log(total_money);
I know this is a simplified version of the code, but just be aware that you are not adding up total_money but overwriting
So if you have another ticker. For example:
var total = 0;
var money1 = 20;
var money2 = 30;
var ticker = [money1,money2];
for (tick in ticker) {
total_money = ticker[tick];
}
console.log(total_money);
You will get total_money = 30, not 50.
You can fix this by doing total_money += ticker[tick]
Also note that you are looping through one item.
The reason is because:
for (tick in ticker) {
console.log(tick) //tick equal 0
}