For loop only running once in Jquery - javascript

Having an issue with a for loop in jQuery only running once. Users is a array containing 4 items, and for each, it should append that item as a list element to userList, which is a ul. It appends the first element in the array as expected, but only that one. Not sure why it isn't running through the entire array?
$(document).ready(function() {
var $currentUser = $('<li class="user"></li>');
for(var i = 0; i < users.length; i++) {
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
//alert(users.length) returns "4".
});

Try this
$(document).ready(function(){
for(var i = 0; i < users.length; i++) {
var $currentUser = $('<li class="user"></li>');
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
});
You're overwriting the element, instead of creating a new one for each user. Try the code above.

More jQuery'ish
$('.userList').append(function() {
return $.map(users, function(user) {
return $('<li />', {
'class' : 'user',
text : user
})
});
});
FIDDLE

You aren't adding a new <li> for each iteration:
Here's a working solution:
for (var i = 0; i < users.length; i++) {
$('<li class="user"></li>'
.text(users[i])
.appendTo('.userList');
}
https://jsfiddle.net/2abqa5us/1/

You create the li on the outside of the loop, then try to set the text of the same element to each user so you will overwrite it every iteration. Are you sure the last entry is not the one you see?

.text will overwrite previous text which looks like you got one users only
try this.
$(document).ready(function(){
for(var i = 0; i < users.length; i++) {
var $currentUser = $('<li class="user"></li>');
$currentUser.text(users[i]);
$currentUser.appendTo('.userList');
}
});

Related

index number for the line time using JavaScript

I am using the below code in the google tag manager custom JavaScript variable, but it returns same index value for every line item, what can be the issue?
Web page link: https://www.amity.edu/programe-list.aspx?fd=all
function() {
var elements = document.querySelectorAll('.staff-container');
for (var i = 0; i < elements.length; i++){
(function(index){
elements[i].children[0].children[0].addEventListener("click", myScript);
function myScript(){
return("Clicked : ",index);
}
})(i);
}
}
There is an error in the 5th line.
It should be elements[index].children... in that case.
The updated code:
function() {
var elements = document.querySelectorAll('.staff-container');
for (var i = 0; i < elements.length; i++){
(function(index){
elements[index].children[0].children[0].addEventListener("click", myScript);
function myScript(){
return("Clicked : ",index);
}
})(i);
}
}
Here is an alternative way from Simo's blog
Blog link
Although the post is say about visibility element. I test it with click on my website.
This might work
function() {
var list = document.querySelectorAll('.staff-container a'),
el = {{Click Element}};
return [].indexOf.call(list, el) + 1;
}
If it is not working, you might need to provide the screenshot about the click element from your GTM preview.

how to delete any content after jquery prepend() inside a loop

i am doing a search button and each time the user searches for a movie, i prepend the photos api in the html div. All i want to do is when a user searches again for another movie i want the previous content to be deleted, ( any content after the prepended one). Here is how my code looks like:
HTML:
<div id="Search-Results"></div>
jQUERY:
$.ajax(settings).done(function (response) {
for(var i=0; i < results.length; i++)
{
var s = '<span><img src="http://example.com/test.jpg"> </span>';
$("#Search-Results").prepend(s);
}
});
Example:
When the user searches for avatar movie and then for godfather, i want the avatar images to be deleted. The godfather will be pretended into the div and the avatar photos that are next to godfather will be removed.
Note that the code is inside a for loop and i get only 1 image with .html
Try this one
$("#Search-Results").html("");
for(var i=0; i < results.length; i++) {
var s = '<span><img src="http://example.com/test.jpg"> </span>';
if (i == 0){
$("#Search-Results").html(s);
}else {
$("#Search-Results").prepend(s);
}
}
For the very first photo in the loop use .html(), use .prepend() for the rest.
for(var i=0; i < results.length; i++) {
var s = '<span><img src="http://example.com/test.jpg"> </span>';
$("#Search-Results")[ i ? 'prepend' : 'html' ]( s );
}
This function will simply overwrite the innerHTML
$("#Search-Results").html(s);

How do I add target=“_blank” to a link within a div with an specific class name?

I´m trying to add target=“_blank” to all the links within the divs with an specific class name. I know how to do it with an ID:
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
But i´m trying to replicate the same, using classes instead of IDS. Any ideas of a how to do this without jquery?.
Thanks in davanced!
You can use querySelectorAll() and include a CSS selector. So if your class name is link-other:
document.querySelectorAll('.link-other a')
.forEach(function(elem) {
elem.setAttribute('target', '_blank');
})
<div class="link-other">
Wikipedia
Google
</div>
Use querySelectorAll and loop just like you did.
var anchors = document.querySelectorAll(".link_other a");
Or you can use getElementsByClassName and nested loops.
var parents = document.getElementsByClassName(".link_other");
for (var i = 0; i < parents.length; i++) {
var anchors = parents[i].getElementsByTagName("a");
for (var j = 0; j < anchors.length; j++) {
anchors[j].setAttribute('target', '_blank');
}
}
You can use document.querySelectorAll() which takes a css expression:
var anchors = document.querySelectorAll('.my_class a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
Or (ab)using the array prototype:
[].forEach.call(document.querySelectorAll('.my_class a'), function(el) {
el.setAttribute('target', '_blank');
});
You should also consider using addEventListener instead of window.onload:
window.addEventListener('load', function() {
// ...
});
Or the more appropriate:
document.addEventListener('DOMContentLoaded', function() {
// ...
});
You can also use the old school <base> element which will can set defaults for all a tags:
var base_el = document.createElement('base');
base_el.setAttribute('target', '_blank');
document.head.appendChild(base_el);
To achieve your expected result use below option
var addList = document.querySelectorAll('.link_other a');
for(var i in addList){
addList[i].setAttribute('target', '_blank');
}
Codepen - http://codepen.io/nagasai/pen/QEEvPR
Hope it works

Toggle is-visible Class to Div Next to Trigger Element (Plain JS)

This is supposed to be a very simple dropdown FAQ system, I know how to do this in jQuery but I want to learn plain JS.
I just want the individual clicked triggers to toggle the is-visible class to the content divs next to the clicked trigger. Like $(this).next addClass — just in JS.
I've really tried to search for this issue but 90% that shows up is how to do it in jQuery :-p
https://jsfiddle.net/48ea3ruz/
var allTriggers = document.querySelectorAll('.faq-trigger');
for (var i = 0; i < allTriggers.length; i++) {
// access to individual triggers:
var trigger = allTriggers[i];
}
var allContent = document.querySelectorAll('.faq-content');
for (var i = 0; i < allContent.length; i++) {
// access to individual content divs:
var content = allContent[i];
}
// I don't know how to target the faq-content div next to the clicked faq-trigger
this.addEventListener('click', function() {
content.classList.toggle('is-visible');
});
Would really appreciate some advice! :-)
Use nextSibling, when you are iterating .faq-trigger
var allTriggers = document.querySelectorAll('.faq-trigger');
for (var i = 0; i < allTriggers.length; i++) {
allTriggers[i].addEventListener('click', function() {
this.nextSibling.classList.toggle('is-visible');
});
}
nextSibling will also consider text-nodes, try nextElementSibling also
var allTriggers = document.querySelectorAll('.faq-trigger');
for (var i = 0; i < allTriggers.length; i++) {
allTriggers[i].addEventListener('click', function() {
this.nextElementSibling.classList.toggle('is-visible');
});
}

how to let jquery select2 disable one option dynamically?

I have some multiselect and i use jquery select2.I want to disable one option in other multiselect when this option is selected in one multiselect.
i write this code,but it does work.
$("select.multiselect").on("change", function(e) {
if(e.added){
for(var i=0;i<this.options.length;i++){
var vals = $(this).select2("val");
for(var j=0;j<vals.length;j++){
if(this.options[i].value===vals[j]){
this.options[i].selected=true;
}
}
};
}
if(e.removed){
for(var i=0;i<this.options.length;i++){
if(this.options[i].value===e.removed.id){
this.options[i].selected=false;
}
};
}
});
how to do it?
It was more complicated then I thought but here is what I came up with:
$('select.multiselect').on('change', function(e) {
// the selected values
var vals = $(this).select2("val");
// selects contains all the OTHER select forms
var selects = $('select').not('#'+$(this).attr('id'));
// loop trough all the selects
for (var i = 0; i < selects.length; i++) {
//re-enable all options before
$(selects[i]).find('option').removeAttr('disabled');
// loop trough all the values
for (var j = 0; j < vals.length; j++) {
// disabled attribute
$(selects[i]).find('option[value='+vals[j]+']').attr('disabled', 'disabled');
}
}
});
Here's a fiddle if you want to see the result in action
Make sure all your select elements have a unique id.

Categories