How to loop function in javascript [duplicate] - javascript

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 8 years ago.
I have same function that I want to make it based on user input ,
for(var u = 1; u <= tmp; u++){
$('#photo_'+u).change(function(){
$('#src_'+u).val($(this).val());
});
Caption: tmp is user input
I try jshint in jsfiddle showing error : "Don't make function withit loop"
how to make that function loop
My question is based in this Link Here

change id and use class:
$('.photo').change(function(){
$(this).find('.src').val($(this).val());
});
change #photo_... and #src_... to class.
$(this) will to point to current .photo element
no need for a loop in this case...

var functionStr="";
for(var u=1;u<=tmp;u++){
if(u==tmp)
{
functionStr=functionStr+"#photo_"+u;
}
else
{
functionStr=functionStr+"#photo_"+u+",";
}
$(functionStr).change(function(){
$('#src_'+u).val($(this).val());
});

Related

Index based argument in for loop of addEventListener [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 2 years ago.
I am adding some JS to an HTML, and I have a fragment of code similar to this:
<script>
function ButtonAction(index){
alert("My index is: "+index);
if(window_big){
// Use index to do something
}
else{
// Use index to do something else
}
}
function WindowResize(){
if(window.innerWidth > 1200){
window_big = true;
}
else{
window_big = false;
}
}
var window_big;
if(window.innerWidth > 1200){
window_big = true;
}
else{
window_big = false;
}
buttons = document.getElementsByClassName('MyButtons')
var i;
for (i = 0; i < buttons.length; i++) {
alert(i);
buttons[i].addEventListener("click",function(){ButtonAction(i);},false);
}
window.onresize = WindowResize;
</script>
The idea can be summarized like this:
There is a series of buttons in the page, stored in buttons[].
If the window is bigger than a certain size, those buttons should do one action, and if not, do another one.
To do said actions, I need the button[x].id. In fact, the initial intention was to set the listener to:
buttons[i].addEventListener("click",function(){ButtonAction(i);},false);
The problem is that I cannot retrieve the id, because the argument passed in the event listener seems to be always the last value i was set to.
May I ask for some help, please?

How to put a text-to-speech in a loop [duplicate]

This question already has answers here:
JavaScript variable binding and loop
(4 answers)
Closed 4 years ago.
I'm using the js library p5.speech. I'm trying to get each strings throught the speech function. However, each time it repeats the same strings.
So is the issue coming from my code or the js library (and in this case, what library should i use?)
const btReport1 = document.getElementById('report1');
btReport1.addEventListener('click', function(e) {
myVoice.setVoice('Google UK English Female');
for(var i=0; i<allData.length;i++){
console.log("allData"+i+" = " + allData[i].profile.length);
// myVoice.speak(allData[i].profile.length+" patients have "+ allData[i].food);;
setTimeout(function afterTwoSeconds() { myVoice.speak(allData[i].profile.length+" dogs have "+ allData[i].food);}, 1000);
}
});
In your for loop, try replacing var with let so that
for(var i=0; i<allData.length;i++){
becomes
for(let i=0; i<allData.length;i++){
For more info, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Assigning a value to an object children with a for loop doesn't work [duplicate]

This question already has answers here:
jQuery AJAX calls in for loop [duplicate]
(2 answers)
Closed 6 years ago.
http://codepen.io/noczesc/pen/ZWppJQ?
function codeToName(data) {
for (var i = 0; i < data.country.borders.length; i++) {
$.getJSON("https://restcountries.eu/rest/v1/alpha?codes=" + data.country.borders[i], function(json) {
data.country.borders[i] = json[0].name;
console.log(json[0].name);
});
}
};
I'm getting an array of country codes which are supposed to be changed to their full representations in English via the codeToName loop and an API, but it only appends a random name to the end of the array. To get a console.log of it, click on the <body>. It's located in JSONextract.country.borders. The country names grabbed via API are correct (logged in console also), but they don't get assigned to the variables inside my object. How can I solve this issue?
for does not work, you should use $.each
function codeToName(data) {
$.each(data.country.borders, function(index,item){
$.getJSON("https://restcountries.eu/rest/v1/alpha?codes=" + item, function(json) {
data.country.borders[index] = json[0].name;
console.log(json[0].name);
});
});
};

Loop through a set of elements jQuery [duplicate]

This question already has answers here:
jQuery Looping and Attaching Click Events
(4 answers)
Closed 7 years ago.
I'm trying to loop through 12 classes, named .video-link0 through video-link11, where each one gets the treatment:
$('.video-link[n]').click(function() {
$('.video-link[n]').addClass('show');
});
Essentially, I want the following behavior:
When .video-link1 is clicked, addClass('show') to video-link1
When .video-link2 is clicked, addClass('show') to video-link2
and so on, as if I had 12 functions that looked like this:
$('.video-link1').click(function() {
$('.video-link1').addClass('show');
});
$('.video-link2').click(function() {
$('.video-link2').addClass('show');
});
... and so on
I want to write a single loop that replaces the need to write this out as 12 separate cases.
The following does not yield the result I'm looking for:
var elems = 12;
for(var i = 0; i < elems; i++){
$('.video-link' + i).click(function() {
$('.video-link' + i).addClass('show');
});
};
** UPDATE **
This is not a duplicate question, or else the above question referenced does not address my requirement. I am not trying to move up and down the DOM with next. Rather, I want to write a single loop that iterates through 12 classes numbered 0-11 using i to enumerate the cases.
** UPDATE **
This works for me, and is using a suggestion by Lloyd Banks (I needed the i enumerator PLUS the this keyword):
for (var i = 0; i < 12; i++) {
$('.video-link'+i).click(function() {
$(this).addClass('show');
});
}
You can use starts with ^= selector and reference each with $(this)
$("[class^='video-link']").click(function() {
$(this).addClass('show');
});
You can use $(this) to reference the current (targeted) element inside of a event callback:
$('.video-link').click(function() {
$(this).addClass('show');
});
You can use
function(numberOfElements){
for(var i = 1; i <= numberOfElements; i++){
$('.video-link' + i).on('click', function(){
$(this).addClass('show');
});
}
}
You should also be using the .on binding event instead of .click. If you are generating your element after initial page load and use .click, the event handler wouldn't be registered.

How do I select elements in jQuery by using a variable for the ID in "Attribute Starts With Selector" [duplicate]

This question already has answers here:
How to use JavaScript variables in jQuery selectors?
(6 answers)
Closed 8 years ago.
Instead of using :
$('input[id^="appName"]').each(function () {
}
});
I would like to use a varibale for Attribute Starts With Selector
var attrName = "appName";
$('input[id^=attrName]').each(function () {
}
});
The above syntax doesn't work. I checked the jQuery documentation and answers here without success.
try
var attrName = "appName";
$('input[id^=' + attrName + ']').each(function () {
// do stuff here
});
http://jsfiddle.net/swm53ran/156/

Categories