accessing first element in js collection - javascript

in my js function I had following
success: function (result) {
$.each(result, function (i, item) {
$("#tab-" + item.myType).append(result);
})
}
Now I've change this function and instead I have following
success: function (result) {
$("#tab-how To Access to the first result collection element ").html(result);
}
}
I tried with
$("#tab-" + result[0].item.myType).html(result);
but it didn't help.
Question is: How to access to the first js element inside result collection object
Any thoughts ?
Using console.log(result) I'm getting html snippets which I display on partial view
div class="product clearfix">
<div class="l-new">
<a href="#">
#Model.MyType (rendered as My Type)
</a>
....
</div>

You can try:
result[0] // if you have numeric indices in your result collection
OR
var firstItem = null;
for(var x in result) { // if you have named properties
firstItem = result[x];
break;
}

Related

Append key value pair in separate tags in HTML using Jquery

I have a json object(stored in a separate file) as follows -
"albums":{
"The Wall" : "1979",
"Pulse" : "1995",
"Meddle" : "1971",
"Animals" : "1977"
}
I want this to be dynamically appended in my DOM as below -
<div>
<p>Key on index i<p>
<p>Value on index i<p>
</div>
The entire div structure should render dynamically as many times as there are entries in the JSON ( in this case 4 times ).
$.getJSON("albums.json",
function (data) {
$.each(data , function (i) {
//append logic here
})
How to achieve this?
Here is a non-jQuery answer
const json = {
"The Wall": "1979",
"Pulse": "1995",
"Meddle": "1971",
"Animals": "1977",
};
for (const key in json) {
//modify element to append elements
document.body.innerHTML += `<div><p>${key}</p><p>${json[key]}</p></div>`;
}
<!DOCTYPE html>
<body>
</body>
Let's separate our concerns. First of all, you need a function with the template:
function myTemplate(key, value) {
return `
<div>
<p>${key}</p>
<p>${value}</p>
</div>
`;
}
So far, so good. Now, let's implement a cycle function:
function myBigTemplate(albums) {
var output = "";
for (let albumKey in albums) output += myTemplate(albumKey, albums[albumKey]);
return output;
}
And then you can put this into a tag, like:
myWrapper.innerHTML = myBigTemplate({"The Wall" : "1979","Pulse" : "1995","Meddle" : "1971","Animals" : "1977"});
The $.each callback function receives the key and value as parameters. Just append each <p> to the DIV with the results.
$.each(data, function(key, value) {
$("#outputdiv").append("<p>", { text: key });
$("#outputdiv").append("<p>", { text: value });
});

how to append nested li from JSON using jquery

I want to bring the json data to front end like in the picture.
How do i do it, here is my code. I want it nested like in the pic below.
This is how far i got with my code.
HTML:
</body>
<div id="active"></div>
</body>
JQuery
<script>
$.getJSON("active.json", function(result){
$.each(result, function(i, field){
var UniqueNames= $.unique(result.map(function (d) {
return d.gpanel;
}));
$("#active").append('<li>'+UniqueNames[i]+'</li>');
});
});
</script>
JSON:
[{"ID":"1","gpanel":"sfd","ptitle":"sdffd","panel":"1,2",
"free":"yes","fees":"0.00"},
{"ID":"2","gpanel":"sdfd","ptitle":"sdfds","panel":"1",
"free":"yes","fees":"0.00"},
{"ID":"3","gpanel":"sdf","ptitle":"sdf","panel":"1",
"free":"yes","fees":"0.00"},
{"ID":"4","gpanel":"sfd","ptitle":"fes","panel":"1",
"free":"yes","fees":"0.00"},
{"ID":"5","gpanel":"bbbfff","ptitle":"hgffg","panel":"1,2",
"free":"yes","fees":"0.00"}
]
thanks in advance.
Solution 1
You can try this code
$.getJSON("active.json", function(result){
var UniqueNames= $.unique(result.map(function (d) {
return d.gpanel;
}));
var ul_block = $("<ul/>");
$.each(UniqueNames, function(i) {
$(ul_block).append('<li>' + UniqueNames[i] + '</li>');
});
$("#active").append(ul_block);
});
I have made some changes in your code,
1) code which is used for fetching uniquenames was removed inside from loop, so that it will not process everytime even though you required once
2) changed the loop from result to UniqueNames, since you are displaying those names only
You can made changes in my code to get required output i.e level of display
Solution 2:
As per the data structure and conditions you provided, Please check this code
$.getJSON("active.json", function(result) {
var panel_arr = ["", "Regular", "Reduced Fee", "Limited Assurance"];
var ul_block = $("<ul/>");
$.each(result, function(i, data) {
console.log(data);
var panels = data.panel.split(",");
var uli_block = $("<ul/>");
$.each(panels, function(j, jdata){
var ulii_block = $("<ul/>");
$(ulii_block).append($("<li/>").text(data.ptitle));
$(uli_block).append($("<li/>").text(panel_arr[panels[j]])).append(ulii_block);
});
$(ul_block).append($("<li/>").text(data.gpanel).append(uli_block));
});
$("#active").append(ul_block);
});

How to call array data corresponding to same array's id

I have an array where each element refers to a bunch of svgs in another js file. I'm trying to get it so that my alert message uses the same string I use in the array variable.
var illustArr = ['map', 'privacy', 'payment', 'rewards', 'passcode'];
var bmAnim = document.getElementById('illus-'+illustArr[i]);
bmAnim.addEventListener('click', function(){
alert('illus-'+illustArr[i]);
});
Any ideas how to achieve that?
You can do it using a for-loop. Also make sure that you check if element exists so that you wont get an error.
var illustArr = ['map', 'privacy', 'payment', 'rewards', 'passcode'];
for (var i = 0; i < illustArr.length; i++) {
bmAnim = document.getElementById('illus-' + illustArr[i]);
if (bmAnim) { //check if element exists
bmAnim.addEventListener('click', function() {
alert('illus' + this.id);
});
}
}
<div id="illus-map">MAP</div>
<p>
<div id="illus-privacy">PRIVACY</div>
<p>
<div id="illus-payment">PAYMENT</div>
<p>
<div id="illus-rewards">REWARDS</div>
<p>
<div id="illus-passcode">PASSCODE</div>
You need to iterate over the array and assign the click function with the corresponding key in scope.
var illustArr = ['map', 'privacy', 'payment', 'rewards', 'passcode'];
illustArr.forEach(function (key) {
var bmAnim = document.getElementById('illus-' + key);
bmAnim && bmAnim.addEventListener('click', function () {
alert('illus-' + key);
});
});
You should use the Array#forEach function to iterate over the elements in your array before you attach any listeners to the click event. Also, you can use this.id in the event handler to reference the string illus-* with the desired suffix rather than accessing illustArr again.
var illustArr = ['map', 'privacy', 'payment', 'rewards', 'passcode'];
illustArr.forEach(function (e) {
document.getElementById('illus-' + e).addEventListener('click', handler)
})
function handler () {
alert(this.id)
}
<ul>
<li id="illus-map">Map</li>
<li id="illus-privacy">Privacy</li>
<li id="illus-payment">Payment</li>
<li id="illus-rewards">Rewards</li>
<li id="illus-passcode">Passcode</li>
</ul>

Get img source from js Object

I have a js object slider.controlNav, that contains DOM elements. I need to save in variable source of image, that contains in link with class 'flex-active'.
jQuery.each(slider.controlNav, function(i, val) {
var dom_object = slider.controlNav.get(i);
console.log(dom_object)
});
Top code returns:
<a href="#0" class="flex-active">
<img src="img/slider-portfolio/logos/__ico__Fason$Active.png">
</a>
<a href="#1>
<img src="img/slider-portfolio/logos/__ico__Web$Active.png">
</a>
<a href="#2" class="flex-active">
<img src="img/slider-portfolio/logos/__ico__New$Active.png">
</a>
My code:
jQuery.each(slider.controlNav, function(i, val) {
var dom_object = slider.controlNav.get(i).find('img').attr('src');
console.log(dom_object)
});
After that in console i have error:
Uncaught TypeError: slider.controlNav.get(...).find is not a function
get function gives you the underlying DOM object. You need to convert it to jQuery object.
Try $(slider.controlNav.get(i)).find('img').attr('src');
Please check with this code.
jQuery("slider.controlNav a").each(function() {
var dom_object = jQuery(this).find('img').attr('src');
console.log(dom_object)
});
You do want to use this or val, which refers to the current element in the iteration:
jQuery.each(slider.controlNav, function(i, val) {
var src = jQuery(this).eq(i).find('img').attr('src');
console.log( src )
});
Alternatively, just use plain JS as follows:
slider.controlNav.forEach(function(val) {
var src = val.querySelector( 'img' ).src;
console.log( src );
});
See this jsbin
var flexActiveControlNavs = slider.controlNav.find(".flex-active");
jQuery.each(flexActiveControlNavs, function(i, val) {
var dom_object = flexActiveControlNavs.eq(i).find('img').attr('src');
console.log(dom_object);
});
This will return only the image sources that are a child of elements with class "flex-active".

Build an array of returned JSON objects to iterate over a list of keywords

Please take a look at this script first, it works fine on my site:
$.ajax({
url: "text.json",
success: function (data) {
var keywords = ["Germany","England","Bayern","ManU"];
$(data).each(function (index, item) {
var nation = item.nation,
club = item.club,
title = item.title;
$.each(keywords,function(i,keyword){
if ($.inArray(keyword,nation)!=-1) {
$('.'+ title+'_'+keyword).html('Yes')
}
else {$('.'+ title+'_'+keyword).html('No')
}
});
},
error: function () { }
});
JSON:
[{"title":"A","club":"Bayern","nation":"Germany"},{"title":"B","club":"Verdy","nation":"Japan"},{"title":"C","club":"ManCity","nation":"England"}]
The script will loop over a list of keywords and check whether they exist in the returned object item.nation.
I want to use the keyword list to check against other returned objects item.title,item.club as well. Can I build an array of the returned objects first to check against the keyword list? I have tried the following but it isn't working:
var keywords = ["Germany","England","Bayern","ManU"];
$(data).each(function (index, item) {
var objects = ['item.nation','item.club','item.title'];
$.each(objects,function(i,object){
$.each(keywords,function(i,keyword){
if ($.inArray(keyword,object)!=-1)
{
$('.'+ title+'_'+keyword).html('Yes')
}
else
{
$('.'+ title+'_'+keyword).html('No')
}
});
});
});
Ideal Output should be like this:
<div class="AGermany>Yes</div>
<div class="BGermany>No</div>
<div class="CGermany>No</div>
<div class="AEngland>No</div>
<div class="BEngland>No</div>
<div class="CEngland>Yes</div>
<div class="ABayern>Yes</div>
<div class="BBayern>No</div>
<div class="CBayern>No</div>
<div class="AManU>No</div>
<div class="BManU>No</div>
<div class="CManU>Yes</div>

Categories

Resources