Creating var in a loop not working Jquery - javascript

I want to get all images src from class '.poi-reviews .poi-review'
however my code is returning only the first image src, always the same first!
what is wrong with my code ?
here it is :
jQuery('.poi-reviews .poi-review').each(function( ) {
var fotos = jQuery('.poi-reviews .author-photo-canvas img').attr('src');
var nome = jQuery('.poi-reviews .review-author-name a').text();
var divImage = "<img id="+nome+" alt="+nome+" height='150 'width='150' src="+ fotos +">" ;
inicio.after(divImage);
});

In jQuery, .each() takes the DOM selection you have made with $("#selection") and iterates over it.
The easiest way to approach this is to have a results array and to push the images' src attributes to it:
JavaScript
var results = [];
$("div > img").each(function () { // selects all img under a div tag and loops through
results.push($(this).attr("src")); // pushes the src attribute of $(this), aka the img,
}) // to the results array
$("#results").text(results.join(", "));
// could also console.log() the results;
// I appended to the DOM so you could easily see it on the fiddle
HTML
<p id="results"></p>
<div>
<img src="http://placekitten.com/200/300" />
<img src="http://placekitten.com/200/200" />
<img src="http://placekitten.com/300/300" />
<img src="http://placekitten.com/300/200" />
</div>
fiddle

That is because there are more than one element so, the attr() call will return the value of only the first element.
You need this:
var fotos = jQuery('.poi-reviews .author-photo-canvas img').map(function() {
return this.src;
}).get();
Now, fotos is a an Array containing the urls. Do what you want with them.

Related

change label foreach element in html using javascript

I am using both html and velocity and came up with this code. The names and images are stored in an array and this is the code I used to display each of the contents of this array to the page.
#foreach($starter in $starter)
<div class="product">
<div class="color"><img src= "$starter.img" width="100" height="100"></div>
<span class="product-name">$starter.name</span>
<div class="compare-wrap">
<input type="checkbox" id="">
<label id="view">Compare</label>
</div>
</div>
#end
I wanted the label to change from "Compare" to "View Compare" while at the same time storing its id in the array upon checking their correspondng check box. I eventually came up with this code:
var checkedArray = [];
$(":checkbox").change(function(){
if((this).checked){
checkedArray.push(this.id);
document.getElementById('view').innerHTML = "<a href='/compare'>View Compare</a>";
}
else{
checkedArray.splice(checkedArray.indexOf(this.id), 1);
document.getElementById('view').innerHTML = 'Compare';
}
var str = checkedArray.join(', ');
alert(str);
});
but it seems it is only applicable to the first content of the array. Any idea how I can use a foreach code at this point?
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You should use a class:
var views = document.getElementsByClassName('view');
var i = views.length;
while(i--) {
views[i].innerHTML = "Compare";
}
HTML
<label class="view">Compare</label>
Element ID must be unique.
Hope it helps.

change span content inside div with dynamic id

I need to change the content of span tag inside of div tag with div id dynamically. I tried this code but it's not working. I think the problem with $('#'+ids[i]). Even I'm getting the information correctly to each id. Any suggestions please.
JavaScript:
var ids = ["Of0UWpK5bEo","1qYMJjTxJnM","8aAab7gxbEg","ZEd6aKdeC8g","qQcFvamzdno","yovbI8DOMpk"];
for (i = 0; i < ids.length; i++) {
$.get("https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id="+ ids[i] + "&key=AIzaSyDEm5wGLsWi2G3WG40re-DAJcWioQSpJ6o", function(data){
$('#'+ids[i]).parent().find('.caption').text(data.items[0].snippet.title);
});
}
HTML:
<div id="Of0UWpK5bEo" class="status">
<img src="http://img.youtube.com/vi/Of0UWpK5bEo/0.jpg" height="100px" width="100px"/>
<span class="caption">Text below the image</span>
</div>
I found it to be the problem of variable scope.
This can be solved by using a anonymous function.
Pass the loop variable i to the anonymous function so that ii will be accessible inside the function.
Check out this fiddle.
Here is the snippet.
var ids = ["Of0UWpK5bEo", "1qYMJjTxJnM", "8aAab7gxbEg", "ZEd6aKdeC8g", "qQcFvamzdno", "yovbI8DOMpk"];
var i;
for (i = 0; i < ids.length; i++) {
(function(ii) { // collect into 'ii' here
$.get("https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id=" + ids[ii] + "&key=AIzaSyDEm5wGLsWi2G3WG40re-DAJcWioQSpJ6o", function(data) {
$('#' + ids[ii]).html(data.items[0].snippet.title);
});
}(i)); //pass 'i' here
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Of0UWpK5bEo" class="status">
<img src="http://img.youtube.com/vi/Of0UWpK5bEo/0.jpg" height="100px" width="100px" />
<span class="caption">Text below the image</span>
</div>
What you need is:
$('#'+ids[i]).find('.caption').text(...);
as .caption is the child of the ID in question itself. Hence, .parent() is not required.
A Demo
Also, use var in your loop as below. You'd create a global for no reason, otherwise.
for (var i = 0; i < ids.length; i++) {
As it turned out, it's due to the async behaviour of $.get() and loop being synchronous. So, your loop has already finshed running whereas you may be at your 1st or 2nd ajax request. What you need to do is scope the id value (based in i) into the ajax request, probably by creating a closure, like below.
var ids = ["Of0UWpK5bEo","1qYMJjTxJnM","8aAab7gxbEg"];
for (var i = 0; i < ids.length; i++) {
(function(id) {
$.get("https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id="+ id + "&key=AIzaSyDEm5wGLsWi2G3WG40re-DAJcWioQSpJ6o", function(data) {
$('#' + id).find('.caption').text(id); //use data.items[0].snippet.title instead of id
});
}(ids[i]));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Of0UWpK5bEo" class="status">
<span class="caption">Text below the image</span>
</div>
<div id="1qYMJjTxJnM" class="status">
<span class="caption">Text below the image</span>
</div>
<div id="8aAab7gxbEg" class="status">
<span class="caption">Text below the image</span>
</div>
Here is a working demo using fiddle echo apis.
This code isn't the best written, but I can explain what is going on.
Your fundamental problem is that the value for "i" is no longer what you expect it to be. By the time the results of the AJAX function have completed, it's an undefined value. The correct way to do this is with an iterator:
$.each(ids, function(index, id) {
$.get("..." + id + "...", function(data) {
$("#" + id).parent().find('.caption').text(data.items[0].snippet.title);
});
});
Also, make sure your code is in a "document.ready()" block or you may not be able to find the elements:
$(document).ready(function() {
$.each(ids, function(index, id) {
$.get("..." + id + "...", function(data) {
$("#" + id).parent().find('.caption').text(data.items[0].snippet.title);
});
});
});
That being said, this looks like the interface should be dynamically created in Javascript. That would allow you to avoid many of the issues with matching IDs in tags and searching for sibling tags since you'd already have the reference.
Working fiddle: https://jsfiddle.net/85jeaoqq/
Here's a slightly better version that dynamically creates the images and caption. It includes code to limit the text to 20 characters: https://jsfiddle.net/x7v2zt6f/

Edit src of img with codemirror

I'm trying to update the src attribute of <img> tags so that the user can insert images to the code from our asset manager.
Consider this HTML:
<div>
<img src="some_image_already_defined.jpg" alt="Some Image" />
</div>
So if the user places the cursor to any position inside the img tag, I'll replace "some_image_already_defined.jpg" with the new image user selected.
The simplified version of code is smt. like that:
var image_path = 'some_new_image.jpg';
$('#insert-image').click(function() {
var cur = codeMirrorHtml.getCursor();
var token = codeMirrorHtml.getTokenAt(cur);
var inner = CodeMirror.innerMode(codeMirrorHtml.getMode(), token.state);
if (inner.state.tagName == 'img') {
var srcPosition = findTheSrcAttributePosition(); // How do I do this?
codeMirrorHtml.setSelection(srcPosition.anchor, srcPosition.head);
codeMirrorHtml.replaceSelection('src="' + image_path + '"');
}
});
So I want to traverse the token somehow but I couldn't find a way to do it.
Step 1
Get the current line number with getCursor:
var line = editor.getCursor().line;
Step 2
Get the contents of the current line using getLine:
var lineTxt = editor.getLine(line);
Step 3
Find the <img tag. This is just a string search and it's up to you:
var imgTagStartIdx = lineTxt.indexOf("<img");

add dynamic id to links using Javascript?

I have many links on a page generated dynamically. Now I want to attach ids to them based on a link just before them.
I have written the following function to return me the value I want to add as id to the href I want.
<script>
function movingid(){
var res = location.href.replace(/.*student\/(.*)\/subject/, '$1');
var subjectid = res.split("/")[2];
var classid = res.split("/")[1];
var sectionid = res.split("/")[0];
return classid+"-"+sectionid+"-"+subjectid;
}
</script>
So what I did is
<a href="javascript:void(0);" id= "javascript:movingid();" >Move To</a>
But the HTML thus generated is not calling the function. Instead its adding the id as plain text form like this id= "javascript:movingid();". How can I call the function?
Please help
Create the links this way:
<a href="javascript:void(0);" id= "" >Move To</a>
Maybe wrapping the links with a div, which gets the id "mylinks". After this call a function adding the id with this code:
i = "1";
$( "div#mylinks a" ).each(function( index ) {
$(this).attr("id",i);
i++;
});
Instead of i take your code from the movingid function you already posted.

how to get src id

<div id="2" class="dsi" onmousedown="test(2);" ondrop="checkImg('2');dropIt(event,2);" ondragover="event.preventDefault();">
<img src="2.gif" draggable="true" ondragstart="dragIt(event,2);" onmousedown="test(1)" id="pic2" />
</div>
I want to get src of img using javascript. How can I do it ?(i wonto get img id using div id.i mean using div id as 2 then result is pic2.)
If you want to get the src of the image then
var imgSrc= document.getElementById("pic2").src;
Using JavaScript
document.getElementById("pic2").getAttribute("src");
Using Jquery
$("#pic2").attr('src')
For the second question you asked in comment on how do we get in case of a loop.
I am assuming your id are like pic1, pic2, .... , pic9
for (i = 1; i <= 9; i++) {
var picId = 'pic' + i;
document.getElementById(picId).getAttribute("src");
}
var imgSrc= document.getElementById("pic2").src;
Try this code
jQuery method :
var youtubeimgsrc = $('#pic2').attr('src');
javascript method :
var youtubeimgsrc = document.getElementById("pic2").src

Categories

Resources