jquery+on iterating loop how can i know which element is clicked - javascript

I am having a list which is nothing but country flag, country name and country code which actually i derived from JSON
and i had written for loop to render the html elements like this
data =
[
{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}]
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div id="listSection">'+
'<div style="display:flex">'+
'<div id="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div id="nameSection">' + countryName + '</div>' +' '+
'<div id="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
also i have a divs section
<div id="inputSection"> </div>
<div id="countries-list">
</div>
and i have done like when you click on input section the list will come and i can choose from the list and i need ONLY the flag should be shown
<script type="text/javascript">
$(document).ready(function(){
$('#countries-list').addClass('hideSection').removeClass('showSection')
});
$('#inputSection').click(function(){
$('#countries-list').addClass('showSection').removeClass('hideSection')
})
</script>
so when i click india JSON from list , i should display indian flag in inputSection again if i click input section list should come and again if i choose NEPAL, indian flag should be replaced with NEPAL flag.
Have 2 problem.First one i am unable to write click function in INNERHTML to identify which country clicked and second how to retrieve the flag section and show it in inputSection.
Any fiddle will be highly helpful and thankful

If all you need is a clone of the flag section in the input section, then this is all you need:
$('.listSection').on('click', function() {
$('#inputSection').html( $('.flagSection', this).clone() );
});
However, you have to convert every occurrence of id in the HTML in your JS to class, as in the working demo below. Id attribute values should be unique.
$(function() {
const data = [{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}];
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div class="listSection">'+
'<div style="display:flex">'+
'<div class="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div class="nameSection">' + countryName + '</div>' +' '+
'<div class="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
$('.listSection').on('click', function() {
console.log( {name: $('.nameSection',this).text(), code: $('.codeSection', this).text()} );
$('#inputSection').html( $('.flagSection', this).clone() );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputSection"> </div>
<div id="countries-list">
</div>
NOTE
Since there's not mention in the documentation of .html( jQueryObject ) even thought it works in the above demo, I'll provide an alternative that uses .empty() and .append() methods:
$('#inputSection').empty().append( $('.flagSection', this).clone() );

Related

How to compare two foreach loop data

I am trying to compare two foreach loop data and display relevant data in a div. As in the following script its comparing data for only first row.
More detail: I want to track a user arrival between two time ranges of the current date, I am fetching user name and,city and arrival time from one table. And expected time ranges of cities from other table as you can see in the response data, When Comparing user arrival time between two time ranges of the city it is comparing for only first row (user) ignoring other rows.
I want to display a button when comparing dates with relevant city of user. If a user arrival date is between city travel start time and end time then the button should be displayed with arrived label else with on the way label.
response = {
"result1": [{
"Name": "Mike",
"city": "London",
"arival_time": "2020-06-06 18:31:57"
}, {
"Name": "milan",
"city": "newyork",
"arival_time": "2020-06-06 20:21:44"
}],
"result2": [{
"city": "london",
"start_time": "08:00:00",
"end_time": "12:00:00"
}, {
"city": "newyork",
"start_time": "06:00:00",
"end_time": "12:00:00"
}]
}
response.result1.forEach(function(element) {
var city = element.city;
response.result2.forEach(function(e) {
const start = e.start_time;
const end = e.end_time;
const check = element.arival_time;
const [date, time] = check.split(" ");
const startDate = `${date} ${start}`;
const endDate = `${date} ${end}`;
const from = new Date(startDate).getTime();
const to = new Date(endDate).getTime();
const target = new Date(check).getTime();
const array = e.city;
const isInArray = array.includes(city);
if (isInArray == true) {
if (target >= from && target <= to) {
$('.action').append('<button type="button" class="med_action pull-right btn btn-success"> Arrived</button>');
} else {
$('.action').append('<button type="button" class="med_action pull-right btn btn-warning"> on the way</button>');
}
}
});
var html = '<div class="details">' +
'<h3><i class="fa fa-exclamation-circle"></i><span> ' + element.Name + '</span></h3>' +
'<div class="form-inline">' +
'<label> city : </label><span> ' + element.city + '</span>' +
'</div>' +
'</div>' +
'<div class="action"></div>' +
'</div>';
$('#container').append(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>
I see two problems with your code:
result1[0].city is 'London' (uppercase) but result2[0].city = 'london' (lowercase) so you won't see any button for Mike.
In the inner loop, the calls to $('.action').append(...) don't have any effect because <div class="action"> doesn't exist until the inner loop has finished.
Here is updated code that buffers the buttons and inserts them into <div class="action">:
response.result1.forEach(function(element) {
var city = element.city;
var buttons = ''; // buffer for buttons
response.result2.forEach(function(e) {
const start = e.start_time;
const end = e.end_time;
const check = element.arival_time;
const [date, time] = check.split(" ");
const startDate = `${date} ${start}`;
const endDate = `${date} ${end}`;
const from = new Date(startDate).getTime();
const to = new Date(endDate).getTime();
const target = new Date(check).getTime();
const array = e.city;
const isInArray = array.includes(city);
if (isInArray == true) {
if (target >= from && target <= to) {
buttons += ('<button type="button" class="med_action pull-right btn btn-success"> Arrived</button>'); // append to buttons var
} else {
buttons += ('<button type="button" class="med_action pull-right btn btn-warning"> on the way</button>'); // append to buttons var
}
}
});
var html = '<div class="details">' +
'<h3><i class="fa fa-exclamation-circle"></i><span> ' + element.Name + '</span></h3>' +
'<div class="form-inline">' +
'<label> city : </label><span> ' + element.city + '</span>' +
'</div>' +
'</div>' +
'<div class="action">' + buttons + '</div>' +
'</div>'; // Insert buttons
$('#container').append(html);
});
See my comments on the lines containing // for explanations of my changes.

Dynamically change carousel images based on click event

I have 3 elements arranged in a row. I want to show a carousel pop-up on click of the columns in the row. The issue is I am not able to change the images of carousal based on selected column element.
Here is my complete code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
width: 70%;
margin: auto;
}
</style>
</head>
<script>
function process() {
var shops = JSON.parse('{ "id": "shopping", "categories": [ { "id": "Amazon", "name": "Amazon", "link": "https://images-na.ssl-images-amazon.com/images/G/01/SellerCentral/legal/amazon-logo_transparent._CB303899249_.png", "images": [ { "href": "https://images-na.ssl-images-amazon.com/images/G/01/credit/img16/CBCC/marketing/marketingpage/products._V524365396_.png" }, { "href": "http://static4.uk.businessinsider.com/image/575adbe2dd0895c4098b46ba/the-50-most-popular-products-on-amazon.jpg" } ] }, { "id": "Google", "name": "Google", "link": "http://pngimg.com/uploads/google/google_PNG19644.png", "images": [ { "href": "https://www.clipartmax.com/png/middle/147-1476512_google-google-products-logos-png.png" }, { "href": "https://xvp.akamaized.net/assets/illustrations/unblock-google/unblock-google-with-a-vpn-fc1e32f59d9c50bae315c2c8506a91e2.png" } ] }, { "id": "Apple", "name": "Apple", "link": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Apple_Logo.svg/2000px-Apple_Logo.svg.png", "images": [ { "href": "https://c.slashgear.com/wp-content/uploads/2018/03/apple-mfi-logos-update-2018-980x620.jpg" }, { "href": "https://support.apple.com/library/content/dam/edam/applecare/images/en_US/applemusic/itunes-apple-logo-apple-music-giftcard.jpg" } ] } ] }');
var row = 1;
var content = "";
shops = shops.categories;
for(var i=0; i< shops.length; i++) {
if(row == 1) {
content += '<div class="row">'
}
content += '<div class="col-md-4 col-sm-12" data-toggle="modal" onclick="processCarousel(shops[i])" data-target="#myModal">';
content += '<img style="border: 1px solid red" src="'+shops[i].link+'" width="100%" height="100%"/></div>';
if(row == 3) {
row = 0;
content += '</div>';
}
row++;
}
document.getElementById("placeholder").innerHTML = content;
processCarousel();
}
function processCarousel(input) {
alert(input);
var m = ['img_chania.jpg','img_chania2.jpg', 'img_flower.jpg','img_flower2.jpg'];
var carouselInner = document.getElementById("carousel-inner");
var carouselIndicators = document.getElementById("carousel-indicators");
var innerContent = "";
var indicatorsContent = "";
for(var i=0 ; i< m.length ; i++) {
var c = "";
if(i == 0) {
c = " active";
}
innerContent += '<div class="item'+c+'"><img src="'+m[i]+'"><div class="carousel-caption"></div> </div>';
indicatorsContent += '<li class='+c+'data-target="#carousel-example-generic" data-slide-to="'+i+'"></li>';
}
carouselInner.innerHTML = innerContent;
carouselIndicators.innerHTML = indicatorsContent;
var carouselExampleGeneric = document.getElementById("carousel-example-generic");
carouselExampleGeneric.carousel();
}
</script>
</html>
The above code generates the below output:
On click of any image it is loading the carousal but the images of carousal are fixed to my array elements var m = ['img_chania.jpg','img_chania2.jpg', 'img_flower.jpg','img_flower2.jpg']; as mentioned in my above code.
But I want to show only the selected images which are present in my input json shops.categories[selectedItem].images
I tried using onclick javascript event on column element, but the code is not recognising it. What is the correct way to do this.
I want to do this using plain javascript.
First you need to get rid of the call to processCarousel(); in line 39.
Your main problem is, that inside of your content variable you are passing the string of the argument variable rather than the argument itself. Try this instead:
content += '<div class="col-md-4 col-sm-12" data-toggle="modal" onclick="processCarousel(' + i + ')" data-target="#myModal">';
This way you are just passing the index of the category that needs to be rendered.
Then you will have to have the shops object available inside of the processCarousel function as well, so I moved it up, outside the function scope.
This will result in further problems inside of you processCarousel function. You will have to set your your images like this var m = shops[i].images; instead of var m = ['img_chania.jpg', 'img_chania2.jpg', 'img_flower.jpg', 'img_flower2.jpg'];
This will throw another error further down.
innerContent += '<div class="item' + c + '"><img src="' + m[i] + '"><div class="carousel-caption"></div> </div>'; will not work. Instead you will have to use m[i].href as your source inside your image tag.
This will now pass the config to the Carousel which will then render just fine.
You might want to think about giving variables speaking names and avoiding variables like 'm'.
var shops = JSON.parse('{ "id": "shopping", "categories": [ { "id": "Amazon", "name": "Amazon", "link": "https://images-na.ssl-images-amazon.com/images/G/01/SellerCentral/legal/amazon-logo_transparent._CB303899249_.png", "images": [ { "href": "https://images-na.ssl-images-amazon.com/images/G/01/credit/img16/CBCC/marketing/marketingpage/products._V524365396_.png" }, { "href": "http://static4.uk.businessinsider.com/image/575adbe2dd0895c4098b46ba/the-50-most-popular-products-on-amazon.jpg" } ] }, { "id": "Google", "name": "Google", "link": "http://pngimg.com/uploads/google/google_PNG19644.png", "images": [ { "href": "https://www.clipartmax.com/png/middle/147-1476512_google-google-products-logos-png.png" }, { "href": "https://xvp.akamaized.net/assets/illustrations/unblock-google/unblock-google-with-a-vpn-fc1e32f59d9c50bae315c2c8506a91e2.png" } ] }, { "id": "Apple", "name": "Apple", "link": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Apple_Logo.svg/2000px-Apple_Logo.svg.png", "images": [ { "href": "https://c.slashgear.com/wp-content/uploads/2018/03/apple-mfi-logos-update-2018-980x620.jpg" }, { "href": "https://support.apple.com/library/content/dam/edam/applecare/images/en_US/applemusic/itunes-apple-logo-apple-music-giftcard.jpg" } ] } ] }');
var row = 1;
var content = "";
shops = shops.categories;
function process() {
for (var i = 0; i < shops.length; i++) {
if (row == 1) {
content += '<div class="row">'
}
content += '<div class="col-md-4 col-sm-12" data-toggle="modal" onclick="processCarousel(' + i + ')" data-target="#myModal">';
content += '<img style="border: 1px solid red" src="' + shops[i].link + '" width="100%" height="100%"/></div>';
if (row == 3) {
row = 0;
content += '</div>';
}
row++;
}
document.getElementById("placeholder").innerHTML = content;
}
function processCarousel(i) {
//var m = ['img_chania.jpg', 'img_chania2.jpg', 'img_flower.jpg', 'img_flower2.jpg'];
var m = shops[i].images;
var carouselInner = document.getElementById("carousel-inner");
var carouselIndicators = document.getElementById("carousel-indicators");
var innerContent = "";
var indicatorsContent = "";
for (var i = 0; i < m.length; i++) {
var c = "";
if (i == 0) {
c = " active";
}
innerContent += '<div class="item' + c + '"><img src="' + m[i].href + '"><div class="carousel-caption"></div> </div>';
indicatorsContent += '<li class=' + c + 'data-target="#carousel-example-generic" data-slide-to="' + i + '"></li>';
}
carouselInner.innerHTML = innerContent;
carouselIndicators.innerHTML = indicatorsContent;
var carouselExampleGeneric = document.getElementById("carousel-example-generic");
//carouselExampleGeneric.carousel();
}

on change of div based drop down jquery

I have a drop down based on a JSON Object and the purpose of this to render a drop down box.
var Regions =
{
"ErrorInfo": {
"Success": true,
"ErrorCode": "",
"Program": "",
"Method": "",
"Message": "",
"Details": "",
"StackTrace": "",
"ErrorList": null
},
"Results": {
"DimName": "region",
"SubsetName": "",
"Members": [{
"ID": "CEurope",
"Name": "Central Europe",
"Children": [],
"Hierarchy": [],
"Attributes": []
},
{
"ID": "SEurope",
"Name": "Southern Europe",
"Children": null,
"Hierarchy": [],
"Attributes": []
}]
}
};
//var htmlStr = '';
var icount=0;
var mySelect = $('#options');
var optionsValues = '<select>';
$.each(Regions, function(){
optionsValues += '<option value="' + Regions.Results.Members[icount].ID + '">' + Regions.Results.Members[icount].Name + '</option>';
icount=icount+1;
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);
This is my Javascript which is working but happy to refine the code so that I can learn the finer points of JS.
My HTML is like this
<!DOCTYPE html>
<html>
<head>
<title>JavaScript & jQuery - Chapter 13: Form Enhancement and Validation - Populate a selectbox</title>
<link rel="stylesheet" href="css/c13.css" />
</head>
<body>
<form name="howHeard" id="howHeard" action="/heard" method="post">
<div id="page">
</div>
<div id="options">
</div>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/124.js"></script>
</body>
</html>
My question is how do I detect an on change event of my drop down list.
Any help would be appreciated as I learn through the maze of jquery javascript etc.
Cheerio
This should do it:
options.change(function() {
alert( "It changed!" );
});
ref: https://api.jquery.com/change/
Some refinement in your JS:
//var icount=0; ->Not needed
//var mySelect = $('#options'); ->Not needed
var optionsValues = '<select id="mySelect">';
$.each(Regions, function(index){
optionsValues += '<option value="' + Regions.Results.Members[index].ID + '">' + Regions.Results.Members[index].Name + '</option>';
//icount=icount+1;-> Not needed
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);
Basically for the above set-up, below code should work:
$("#mySelect").on('change',function(){
//do stuff here
});
Or if its dynamic element the below should definitely work:
$(document).on('change',"#mySelect",function(){
//do stuff here
});
UPDATE
WORKING DEMO TO CLARIFY YOUR DOUBTS
Bit more refinement on your JS:
var members=Regions.Results.Members; //Get all the members in a single variable
var optionsValues = '<select id="mySelect">';
//loop here for only member variables
$.each(members, function(index,value){
optionsValues += '<option value="' + value.ID + '">' + value.Name + '</option>';
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);

Creating an array of containers using jquery

Template:
<Div id='Container'>
<div id='name'></div>
<div id='address'></div>
</div>
I want to then use this template by using a for loop to replicate it with the name and address within each container being different.
I don't want to recreate the whole template dynamically, as the template will never change.
So the output on the body should be like this:
<Div id='Container'>
<div id='name'></div>
<div id='address'></div>
</div>
<Div id='Container1'>
<div id='name'></div>
<div id='address'></div>
</div>
<Div id='Container2'>
<div id='name'></div>
<div id='address'></div>
</div>
Output on body:
Container:
Tom
sample address
Container 1:
Richard.
address 2
Container 3:
John
address 3
Try this:
for(var i = 0; i < 4; i++){
var container = document.createElement('div'),
name = document.createElement('div'),
address = document.createElement('div');
container.id = 'Container' + i;
name.className = 'name';
address.className = 'address';
container.appendChild(name);
container.appendChild(address);
document.body.appendChild(container);
}
//same thing using jQuery + people array for easy population
var people = [
{name: "Tom", address: "sample address"},
{name: "Richard", address: "address 2"},
{name: "John", address: "address 3"}
];
for(var i = 0, len = people.length; i < len; i++){
var container = $("<div id='Container" + i + "'><div class='name'>" + people[i].name + "</div><div class='address'>" + people[i].address + "</div></div>");
$('body').append(container);
}
The answer above is pure javascript and of course works, but you asked how to do it in jQuery, so here's a jQuery version using the $.each() method to iterate over an array of objects:
var mydata = [{"name": "Tom", "address": "123 Happy Land"},{"name": "Dick", "address": "456 Main Street"},{"name": "Harry", "address": "789 End of the World"}]
$.each(mydata, function() {
var template = '<div class="container">';
template += '<div class="name">'+this.name+'</div>';
template += '<div class="address">'+this.address+'</div>';
template += '</div>';
$('body').append(template);
});
EDIT:
If you need your containers numbered with an unique id that's easy too:
var mydata = [{"name": "Tom", "address": "123 Happy Land"},{"name": "Dick", "address": "456 Main Street"},{"name": "Harry", "address": "789 End of the World"}]
$.each(mydata, function(index) {
index=index+1; //so you start at 1 not 0
var template = '<div id="container'+index+'">';
template += '<div class="name">'+this.name+'</div>';
template += '<div class="address">'+this.address+'</div>';
template += '</div>';
$('body').append(template);
});

innerHTML is not getting updated

I am trying to get the data from the string and i want to display it in my html.
Here is the code what i tried
var jsn = {
"channels": [{
"name": "video1",
"image": "images/bodyguard.jpg"
}, {
"name": "video2",
"image": "images/bodyguard.jpg"
}, {
"name": "video3",
"image": "images/bodyguard.jpg"
}, {
"name": "video4",
"image": "images/bodyguard.jpg"
}, {
"name": "video5",
"image": "images/bodyguard.jpg"
}]
};
var id = document.getElementById("menu_list");
var inHtm = "";
var channels = jsn.channels.length;
var cha = jsn.channels;
alert("channels : " + channels);
if (channels != undefined) {
for (var i = 0, len = channels; i < len; ++i) {
var item = cha[i].name;
alert(item);
//var name = item.name;
var image = cha[i].image;
inHtm += '<div class="menu"><a href="javascript:void(0);" onkeydown="Main.keyDown();" >';
inHtm += '<img src="' + image + '"/>';
inHtm += '</a></div>';
}
alert(inHtm);
in1.innerHtml = inHtm;
}
My Fiddle
It is assigning the values to inHtm but my innerHTML is not getting updated. I want to display the image in my html
This:
in1.innerHtml = inHtm;
Should be:
id.innerHTML = inHtm;
Your object is id not in1 and the property is innerHTML not innerHtml.
Also I suggest using console.log() for degbugging instead of alert(). alerts are painful especially in loops, and with console.log() you can dump entire objects, whereas alert will just show "object".
Corrected fiddle

Categories

Resources