on change of div based drop down jquery - javascript

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);

Related

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

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() );

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();
}

How to create tables in jQuery for $.each()

I am a beginner programmer that is trying to display data results I get from Etsy API into a table as shown below:
<tr><td>item.images</td><td><tr>item.title</tr><tr>item.price</tr></tr>
However, I am unable to display the results in a table and am having problems applying the solutions to my situation
Here is the set of working codes, and I have commented out my failed attempts.
<script type="text/javascript">
(function($){
$(document).ready(function(){
$('#etsy-search').bind('submit', function() {
api_key = "XXXXXXXXXXXXXXXXXXXXX";
terms = $('#etsy-terms').val();
etsyURL = "https://openapi.etsy.com/v2/listings/active.js?keywords="+
terms+"&limit=3&includes=Images:1&api_key="+api_key;
$('#etsy-images').empty();
$('<p></p>').text('Searching for '+terms).appendTo('#etsy-images');
$.ajax({
url: etsyURL,
dataType: 'jsonp',
success: function(data) {
if (data.ok) {
// Commented out are my failed attempt
//var table = "<table>";
$('#etsy-images').empty();
if (data.count > 0) {
$.each(data.results, function(i,item) {
$("<img/>").attr("src", item.Images[0].url_75x75).appendTo("#etsy-images").wrap(
"<a href='" + item.url + "'></a>"
//table+='<tr><td>'+item.title+'</td><td>'+item.price+'</td></tr>';
//}
);
// table+='</table>';
// $("#etsy-images").html( table );
if (i%4 == 3) {
$('<br/>').appendTo('#etsy-images');
}
});
} else {
$('<p>No results.</p>').appendTo('#etsy-images');
}
} else {
$('#etsy-images').empty();
alert(data.error);
}
}
});
return false;
})
});
})(jQuery);
</script>
<body>
<form id="etsy-search">
<input id="etsy-terms" size="32">
<button>Search!</button>
</form>
<div id="etsy-images"></div>
</body>
Additional info:
1. Currently the results looks like this:
After a successful search, the JSON results looks like this:
[
{
"listing_id": 123,
"state": "active",
"user_id": 123,
"category_id": 123,
"title": "XXX",
"price": "2.99",
"currency_code": "USD"
....
}
]
I eventually used trHTML to format the table:
var trHTML = '';
$('#etsy-table').empty();
$.each(data.results, function(i,item) {
trHTML += '<tr><td>' + '<a href="'
+ item.url +'" target="_blank" style="color: white"><img src="'
+ item.Images[0].url_75x75 + '" border="0"></a></td><td><tr>'
+ item.title + '</tr><tr>'
+ item.price + '</tr><tr><a href="'
+ vimg +'" target="_blank" style="color: white"><img class="autosizeImage"src="'
+ vimg + '" border="0"></a></tr></td></tr>';
})
$('#etsy-table').append(trHTML);
Firts step check the "crossdomain" someones browsers don't allow get data between different domains, you can enabled it with headers to allow than.

Not being able to filter json data by just name

I have a file called data.json and a file called Search.html. The xbox360 json file contains:
[{
"Name": "Assassin's Creed: Rogue",
"Image": "Images/360ACR.jpg",
"Platform": "XBOX 360"
}, {
"Name": "Battlefield 3",
"Image": "Images/360BF3.jpg",
"Platform": "XBOX 360"
}]
The Search html file contains:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#search').keyup(function() {
var searchField = $('#search').val();
var regex = new RegExp(searchField, "i");
var output = '<div class="row">';
var count = 1;
$.getJSON('data.json', function(data) {
$.each(data, function(key, val) {
if ((val.Name.search(regex) != -1) || (val.Platform.search(regex) != -1)) {
output += '<div class="col-md-6 well">';
output += '<div class="col-md-3"><img class="img-responsive" src="' + val.Image + '" alt="' + val.Name + '" /></div>';
output += '<div class="col-md-7">';
output += '<h5>' + val.Name + '</h5>';
output += '<p>' + val.Platform + '</p>'
output += '</div>';
output += '</div>';
if (count % 2 == 0) {
output += '</div><div class="row">'
}
count++;
}
});
output += '</div>';
$('#results').html(output);
});
});
});
</script>
</head>
<body>
<form>
<div class="form">
<input type="text" class="" id="search" placeholder="Search">
<input type="button" id="search" value="Search" />
</div>
</form>
<div id="results"></div>
</body>
</html>
The problem with this code is that when the user types a or any letter into the textbox it brings up all the data from the JSON file. I just want it to filter it by name. So if I type Assassins Creed it just brings up that game only.
I know this question is tedious with the amount of code I have put in. It would be nice for someone to help me. I appreciate it if you can. I am trying by the way.
Try using a filter:
var res = data.filter(function(obj){
return obj.Name.indexOf(input) >= 0;
});
The array of objects you want will be in res.
Replace input with the string you want to check for.
See this JSFiddle: https://jsfiddle.net/4b5gffmu/

JSON not working in Firefox but in Chrome and Safari it works as expected

I've a list that autopopulates from a JSON file:
<div class="conversionFormES" id="from1">
<label for="from">Convert From:</label>
<select size = "10" name="from" id="from" onchange="convertUnits()">
<option value="from">-Select an Option-</option>
<option value="from">Firefox</option>
</select>
</div>
I added the 'Firefox' option just to make sure something was being displayed and it is.
Any ideas what the problem could be. Just to re-iterate, it works perfectly with chrome and safari. Many thanks.
ConvertUnits function:
function convertUnits(){
var convertObj = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
var measurementType = $("#from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(convertObj.units.val());
// convertObj.convertUnitsFromHash();
if(measurementType == "temp"){
convertObj.convertTemp();
}else{
convertObj.convertUnitsFromHash();
}
console.log('Measurement Type:', measurementType);
}
JSON Script called after the HTML Form.
<script>
// JSON:
// The key is the class identifier, temp, area etc etc
// Value is being used for both ID and Value when the list is being populated
$(document).ready(function(){
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
});
</script>
EDIT: JSON sample:
{
"angle": [
{
"value": "degree",
"name": "Degree(deg)"
},
{
"value": "radian",
"name": "Radian(rad)"
}
]
}

Categories

Resources