I have array of values and i want to set those values as placeholders to my input.
How to achieve this using jQuery.each() only because i solved my issue with this solution and it works perfectly.
I tried doing this to restart it but it's not working:
if(index==arr.length) index=0;
HTML code:
Values : <input name='input' id='input' />
JS/jQuery code:
var arr = new Array();
for (var i = 0; i <= 5; i++) {
arr.push('Value ' + i);//fill array with values
}
function eachChange(){
var x=0;
$.each(arr, function (index, value) {
x++;
setTimeout(function(){
$('input').attr('placeholder', value);
}, x * 1000);
if(index==arr.length) index=0;
});
}
eachChange();//call function
Fiddle: http://jsfiddle.net/charaf11/5ZQgX/
There are two issues with trying to restart a .each() loop this way. First and foremost, that's not how .each() really works. It's less a loop and more shorthand for calling the function on every element. If you gave that anonymous function a name (let's go with setPlaceholder()), the .each() call is essentially doing this:
setPlaceholder(0, arr[0]);
setPlaceholder(1, arr[1]);
setPlaceholder(2, arr[2]);
setPlaceholder(3, arr[3]);
setPlaceholder(4, arr[4]);
setPlaceholder(5, arr[5]);
The index value it passes to the function isn't used for looping purposes, so trying to set it to 0 won't have any impact on the .each() call.
The second issue is your if condition. It'll never actually fire, since the final "iteration" of the .each() call will have arr.length - 1 as its value, not arr.length.
I'm not sure why you want to have it keep looping, but if that's your goal, you could accomplish it like this:
function eachChange(){
$.each(arr, function (index, value) {
setTimeout(function() {
$('input').attr('placeholder', value);
}, index * 1000);
if (index == arr.length - 1) {
setTimeout(eachChange, (index + 1) * 1000);
}
});
}
eachChange();//call function
What that should do is schedule eachChange() to be called again 1 second after the last placeholder update takes place. You can add in some other checks to limit the number of times it recurses, but if you want it to happen indefinitely that should do the trick.
Here's an updated fiddle demonstrating it.
you can compare the index with the arr.length like this
var arr = new Array();
for (var i = 0; i <= 5; i++) {
arr.push('Value ' + i);//fill array with values
}
function eachChange(){
$.each(arr, function (index, value) {
setTimeout(function(){
$('input').attr('placeholder', value);
//if it is the last element in arr setTimeout and call eachChange()
if(index>=arr.length-1){
setTimeout(function(){
eachChange();
},1000);
}
}, index * 1000);
});
}
eachChange();
http://jsfiddle.net/R274P/1/
I dont think you can reset the counter of the $.each function, as it seems to encapsulate a simple for loop. You dont have access to the counter from the outside.
However, try:
function eachChange(initX){
var x = initX || 0;
$.each(arr, function (index, value) {
x++;
setTimeout(function(){
$('input').attr('placeholder', value);
}, x * 1000);
// Call yourself but pass current x
if(index==arr.length) eachChange(x);
});
}
Remove the initX part if you want x to reset, but i assume you want it to keep counting from where the previous loop finished.
Related
I have a bit of code that counts how many objects are in the returned json and gives me the total number.
loadCountSetOne = 0;
$.each(dataSetOne.user.customers, function(key, val) {
loads = Object.keys(val.loads).length;
loadCountSetOne = loadCountSetOne + loads;
console.log(loadCountSetOne);
});
This works fine, but since I'll need to count these a bunch of times I thought I'd move it into it's own function and call it when I need it with something like counter(val.loads);
count = 0;
function counter(itemToCount) {
result = Object.keys(itemToCount).length;
count = count + result;
console.log(itemToCount, result, count);
return count;
}
When I call the function the 1st time I get the right result. When I call it again it adds the 2nd result to the 1st and so on.
My understanding is that that is what it's supposed to do, but not what I need it to do. I tried resetting the value for count is various places but it didn't work.
Is there a way to make this function give me a result based on the number of objects in itemToCount each time it's called?
Thanks.
You can't do this in the counter() function itself, since it has no way of distinguishing the first call (which should reset the variable) with subsequent calls. You could pass the array index, and it could reset the total when the index is 0, but this is not a good general solution because you might want to use the function in other ways.
You just need to reset the variable before the $.each() loop:
count = 0;
$.each(dataSetOne.user.customers, function(key, val) {
counter(val.loads);
});
Or you could use reduce, which is designed for accumulating values.
function counter(total, itemToCount) {
var result = Object.keys(itemToCount).length;
total += result;
console.log(itemToCount, result, total);
return total;
}
var count = dataSetOne.user.customers.reduce(function(total, current) {
return counter(total, current.loads);
}, 0);
Currently I have a closure in JS that looks like the following:
var addTo = function(num){
var add = function(inner){
return inner + num;
};
return add;
};
var sum = new addTo(1);
My goal is to use the above closure to compute the sum from 1 all the way to 100 (i.e. sum = 1+2+3+...+99+100). Any help? I know a loop is needed, but am unsure of what should go inside the loop and how to use closure to achieve the goal. Thanks guys.
Currently I have a closure in JS that looks like the following:
All functions create closures, they're only remarkable when advantage is taken of them. ;-)
var addTo = function(num){
I don't know why function expressions are used when declarations are clearer (to me):
function addTo(num) {
then there's:
var add = function(inner){
return inner + num;
}
return add;
}
Which (sticking with an expression) can be:
return function (inner) {return inner + num};
}
Then you call it with new:
var sum = new addTo(1);
which causes addTo to create a new object that is not used, so you might as well do:
var sum = addTo(1);
which produces exactly the same result. So:
function addTo(num) {
return function (inner) {return inner + num};
}
var sum = addTo(1);
document.write(sum(3));
However, this is really just a version of Currying, so that sum will just add the supplied value to whatever was initially supplied to addTo.
If you want to add all the numbers from 0 to some limit, you just need a loop, no closure required:
function sumTo(num) {
var total = 0;
for (var i = 0; i <= num; i++) {
total += i;
}
return total;
}
document.write(sumTo(5)); // 15
Note that supplying a negative number will result in an endless loop, you should protect against that (I'll leave it up to you to work out how).
Try
function sum(x) {
var input = x;
function add(y) {
return input + y;
}
return add;
}
//var sum1 = sum(2);
//console.log(sum1(3)); // 5
console.log(sum(2)(3)); //5
Maybe you want to use recursive instead of loops?
function addTo(initial) {
function add(adder) {
if (initial < 100) {
initial+=1
return add(adder+initial)
}
else {
return adder
}
}
return add(initial)
}
document.write(addTo(1))
As long as the initial values don't go over 100, it would just add with sum of all calculation before + itself + 1.
It looks like the addTo() function returns another function into sum that will add whatever you pass it to the original number (or I assume that's what you meant to write; the first thing to do is change the statement inside of add() to use a += instead of just + to make sure you save the result).
Since you want to add each number from 2 to 100 (since you already passed 1 into addTo()), try writing a for loop that runs from 2 to 100 passing each one into the sum() function to add them all together. Here's an example:
var sum = addTo(1);
for (var i=2; i<100; i++) sum(i);
var result = sum(100);
Here I added 100 after the loop since I wanted to grab the final result. You could also add 100 in the loop and use sum(0) to get the result without changing it after the loop.
I am trying to mix the initial string and randomly compare the string's elements with the right elements on the right indexes, and if true push them into a set, to reconstruct the initial string. Doing this I met the problem that while loop does nothing just crushng the browser. Help me out with this.
function checker() {
var text = document.getElementById("inp").value;
var a = [];
var i = 0;
while (a.length < text.length) {
var int = setInterval((function() {
var rnd = Math.floor(Math.random() * text.length);
if (text[rnd] === text[i]) {
a.push(text[rnd]);
clearInterval(int);
i++;
}
}), 100)
}
}
P.S. I need the setInterval() function because I need the process to happen in exactly the same periods of time.
So, you stumbled into the pitfall most people hit at some point when they get in touch with asynchronous programming.
You cannot "wait" for an timeout/interval to finish - trying to do so would not work or block the whole page/browser. Any code that should run after the delay needs to be called from the callback you passed to setInterval when it's "done".
In my answer its doing exactly what you want - creating exactly the same string by randomly mixing the initial, and also using setInterval. You didn't write where you want the result, so you have it written in the console and also in another input field with id output_string.
HTML:
<input id="input_string" value="some_text" />
<input id="output_string" value="" readonly="readonly" />
JavaScript:
function checker() {
var text = document.getElementById("input_string").value;
var result = '';
// split your input string to array
text = text.split('');
var int = setInterval((function() {
var rnd = Math.floor(Math.random() * text.length);
// add random character from input string (array) to the result
result += text[rnd];
// remove used element from the input array
text.splice(rnd, 1);
// if all characters were used
if (text.length === 0) {
clearInterval(int);
console.log(result);
document.getElementById("output_string").value = result;
}
}), 100);
}
checker();
DEMO
Honestly, I have no idea what you are trying to do here, but you seem to have lost track of how your code is operating exactly.
All your while loop does, is creating the interval, which is ran asynchronous from the loop itself.
In other words, the only way your while condition equates to false, is after multiple 100ms intervals have elapsed. 100 miliseconds is an eternity when comparing it to the speed of 1 loop iteration. We're looking at 1000s of iterations before your first setInterval even triggers, not something a browser can keep up with, let alone wait several of these intervals before you change a.length.
Try more like this:
function checker() {
var text = document.getElementById("inp").value;
var a = [];
var i = 0;
// start to do a check every 100ms.
var interv = setInterval(function() {
var rnd = Math.floor(Math.random() * text.length);
if (text[rnd] === text[i]) {
a.push(text[rnd]);
i++;
}
// at the end of each call, see if a is long enough yet
if(a.length > text.length){
clearInterval(interv); // if so, stop this interval from running
alert(a); // and do whatever you need to in the UI.
}
}, 100);
}
}
I suppose this is a newbie question, but I can't seem to figure it out. I have this code, from eloquent javascript, about the reduce function:
function forEach ( info, func ) {
for ( i = 0; i < info.length; i++) {
func(info[i]);
}
}
function reduce (combine, base, array) {
forEach(array, function(elem) {
base = combine(base, elem);
console.log("The base is: " + base);
});
return base;
}
function countZeroes(array) {
function counter(total, element) {
console.log("The total is: " + total);
return total + (element === 0 ? 1 : 0);
}
return reduce(counter, 0, array);
}
What I can not figure out is, how is the number of zeroes stored in total through each call of the function? Why does it keep a running tab, instead of getting wiped out each time?
The structure of reduce is that it applies a function f which takes two operands - here called element and total to a sequence. element is the next unprocessed item in the sequence (array); total is the result of the previous call to f.
Conceptually reduce(f, 0, [1,2,3]) expands to f(3,f(2,f(1,0).
Now, to answer your question: the running total is stored between invocations of counter in the variable base inside reduce.
I need to Loop in JQuery from 0 to variable-value(dynamically entered by user).How can i achieve this?
Now i am doing it by using simple For loop like this.
for( i=1; i<=fetch; i++) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Thanks.
You could loop an empty array:
$.each(new Array(fetch), function(i) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
});
If you do this alot you can even fake-patch jQuery.each to take numbers:
(function($) {
var _each = $.each;
$.each = function() {
var args = $.makeArray(arguments);
if ( args.length == 2 && typeof args[0] == 'number') {
return _each.call(this, new Array(args[0]), args[1]);
}
return _each.call(this, args);
};
}(jQuery));
$.each(fetch, function(i) {
// loop
});
jQuery.each does have some great features, like the different return values inside the callback. But for a simple loop I find it much more convenient (and less overhead) to do something like:
while(fetch--) {
// loop
}
To loop between two values you should use a regular Javascript loop. The jQuery each methods are used when looping through a collection of elements or an array.
To loop from zero, you should initialise the loop variable to zero, not one. To loop from zero to the specified value, you use the <= for the comparison, but to loop from zero and the number of items as specified (i.e. from 0 to value-1), you use the < operator.
for (i = 0; i < fetch; i++) {
$('body').append($('<input/>', { type: 'text' }));
}
You mean Javascript loop.
From W3Schools:
for (var variable = startvalue; variable < endvalue; variable = variable + increment)
{
//code to be executed
}
To get the value from user and run the code you can use the following prompt.
var x=prompt("Enter the value",0);
for(i=0;i<x;i++)
{
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Hope this helps.
Thanks
If you want it the full jQuery way then use that new plugin jQuery-timing. It provides inline-loops in your jQuery line:
$('body').repeat().append('<input>').until(fetch);
Nice, eh?