Situation: Using a Rails app, and $http.get in AngularJS to PULL the photos from Edmunds.com MEDIA API.
TASK TRYING TO COMPLETE: ng-repeat through the vehicle photos.
CONDITIONS: I am getting the response successfully and able to load one image, but how can I have it repeat through the photos array and do all the images.
Apologies for unclear explanation, and any help appreciated.
index.html:
<h1> Wheel Tire Family </h1>
<!-- CAR IMAGES -->
<div ng-init="carImages">
<img src="https://media.ed.edmunds-media.com/{{carImages}}">
</div>
catalog_controller.js:
$scope.photos = {};
$scope.carImages = {};
//GET the edmunds media api for the
//Make Model Year photos
$http.get("https://api.edmunds.com/api/media/v2/audi/a3/2015/photos?title=&category=exterior&provider=oem&width=1280&shottype=S&pagenum=1&pagesize=10&view=basic&api_key=api_key&fmt=json")
.success(function (data) {
var photos = data;
console.log(photos);
$scope.carImages = photos.photos[0].sources[0].link.href;
console.log($scope.carImages);
});
Maybe something like this?
angular
.success(function (data) {
$scope.carImages = data.photos;
});
html
<div ng-repeat="carImage in carImages">
<img ng-src="https://media.ed.edmunds-media.com/{{carImage.sources[0].link.href}}">
</div>
This should loop through the images and pick the first "source" link. It is also recommended that you use ng-src instead of src.
I have some helpful code for you in Jquery, may be this could help in working out with angular js.
To get all Vehicle Details (New, Used, Future) using Jquery , Use the below code.
<!--Form Details to display year/make/model in dropdown -->
<form method="POST" action="one123.php">
<select id="ajYears" name="ajYears">
</select>
<select id="ajMakes" name="makes" disabled="disabled">
<option>Select Make</option>
</select>
<select id="ajModels" name="models" disabled="disabled">
<option>Select Model</option>
</select>
<select id="ajStyles" name="styles" disabled="disabled">
<option>Select Trim</option>
</select>
<input type="submit" value="submit">
</form>
<!--Script to fetch details from API-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
jQuery.noConflict();
</script>
<!-- js code -->
<script>
var protoCall = "https://";
var host = "api.edmunds.com";
// Make sure to change the API KEY
var apiKey = "API KEY";
var fmt = "json";
var standardParams = "&fmt=" + fmt + "&api_key=" + apiKey + "&callback=?";
var $yearSelect = jQuery('#ajYears');
var $makeSelect = jQuery('#ajMakes');
var $modelSelect = jQuery('#ajModels');
var $styleSelect = jQuery('#ajStyles');
// lets bind some events on document.ready.
jQuery(function(){
$yearSelect.on('change', function() { getMakeModelsByYear()});
$makeSelect.on('change', function() { enableModelDropdown() });
$modelSelect.on('change', function() { getStyles() });
// lets build the year drop down.
ajEdmundsBuildYear();
});
// method to build the year drop down.
function ajEdmundsBuildYear()
{
var baseYear = 1990,
endYear = new Date().getFullYear();
$yearSelect.empty();
$yearSelect.append('<option value="-1">Select Year</option>');
for(var yyyy=baseYear; yyyy<=endYear; yyyy++)
{
$yearSelect.append('<option value="' + yyyy + '">' + yyyy +'</option>');
}
}
// get the makes and models for a year in one go...
function getMakeModelsByYear()
{
var year = $yearSelect.val(),
endPoint = "/api/vehicle/v2/makes",
view = "basic",
options = "year=" + year + "&view=" + view + standardParams,
postURL = protoCall + host + endPoint + "?" + options;
jQuery.getJSON(postURL,
function(data) {
// clear the make drop down... re add the first option... remove dsiabled attr.
$makeSelect.empty();
$makeSelect.append('<option value="-1">Select Make</option>');
$makeSelect.removeAttr('disabled');
$modelSelect.empty();
$modelSelect.append('<option value="-1">Select Model</option>');
// loop the makes... each make contains model... add the make in make drop down and models in model dd
jQuery.each(data.makes, function(i, val) {
make = data.makes[i];
$makeSelect.append('<option value="' + make.niceName + '">' + make.name + '</option>');
jQuery.each(make.models, function(x, val){
model = make.models[x];
$modelSelect.append('<option make="' + make.niceName +'" value="' + model.niceName + '">' + model.name + '</option>');
});
});
});
}
// since we already grabed the models...
// now just matter of showing only the matching models for a make.
function enableModelDropdown()
{
var make = $makeSelect.val();
$modelSelect.removeAttr('disabled');
$modelSelect.find('option').not('[value="-1"]').hide();
$modelSelect.find('option[make=' + make + ']').show();
}
// grab the styles... pretty much same as
// getMakeModelsByYear()
function getStyles()
{
var year = $yearSelect.val(),
make = $makeSelect.val(),
model = $modelSelect.val(),
endPoint = "/api/vehicle/v2/" + make + "/" + model + "/" + year + "/styles",
view = "basic",
options = "view=" + view + standardParams,
postURL = protoCall + host + endPoint + "?" + options;
jQuery.getJSON(postURL,
function(data) {
$styleSelect.empty();
$styleSelect.removeAttr('disabled');
$styleSelect.append('<option value="-1">Select Style</option>');
jQuery.each(data.styles, function(i, val) {
style = data.styles[i];
$styleSelect.append("<option value='" + style.id + "'>" + style.name + "</option>");
});
});
}
Related
Currently making a website to index and play movies stored on my hard drive that I've recently pulled off dvds just as a little side project. I have a 'master movie list' JSON file with all the data I need for each movie including the name, video source, video poster source, and genre which I would like to allow the use of placing a movie in multiple different genres.
Currently the problem I'm having is while I'm parsing through the genre list generated its not placing the html in the correct ID that id like it to on the webpage.
For example:
"genre":"comedy,recent,scifi"
I went about it how I thought I should, through getJSON and setting an output variable to which I get the genre value, split to make it an array, and get the element by going through each of them in a loop. Its not placing it in the right place though. The example above would be placed in comedy, recent, scifi, horror, and a few others for some reason and I have absolutely no reason why.
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
var output = '';
var ele = $('');
$.each(data, function(key, val) {
output += '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.html(output);
}
});
});
[ {
"name": "a star is born", "video_src":"/files/movies/A%20Star%20Is%20Born/astarisborn.mp4", "video_poster_src":"https://images-na.ssl-images-amazon.com/images/I/51R-TU6VaTL.jpg", "genre":"recently,romance,drama"
}
] // this is an example of the json
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="genre_box">
<h3>RECENTLY ADDED</h3>
<div class="scroll_box" id="recently"></div>
</div>
<div class="genre_box">
<h3>ACTION</h3>
<div class="scroll_box" id="action"></div>
</div>
<div class="genre_box">
<h3>COMEDY</h3>
<div class="scroll_box" id="comedy"></div>
</div>
Your output variable is being appended to and kept on every iteration of your $.each loop. What you want is to append to the end of $("#action"), $("#comedy"), etc. You should do something along these lines:
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
$.each(data, function(key, val) {
var output = '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (var i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.append(output);
}
});
});
So, I am building some sort of e-commerce website and I needed to import a bunch of products from a mysql database, using nodejs and ajax.
I've been able to get that so far, aswell as creating certain buttons below each product that will lead to a /product page where additional information will be displayed of that exact product.
Since those buttons were not dynamic, I had the need to add an attribute, which will contain the products ID, which I will then use to send a POST request to the server so I can get the information about that specific product.
And although I was able to add the attribute to the buttons themselves, I have no idea how to get their value.
This is how I added my attributes to the buttons.
$(function () {
$.ajax({
type: 'POST',
url: '/getPacotes',
success: function (data) {
for (var i = 0; i < data.length; i++) {
var idPacote = data[i].idPacote;
var nomePacote = data[i].Nome_Pacote;
var precoPacote = data[i].Preco_Pacote;
var fornecedorPacote = data[i].Fornecedor_Pacote;
var foto = "https://webitcloud.net/PW/1617/RMR/Views/images/Pacotes/" + data[i].Foto;
var pacoteSet1 = "<div class='col-md-4 pacotes'>";
var pacoteSet2 = "<img src=" + foto + " alt='Mountain View' style='width:150px;height:150px;'><br><br><input id=btnPac" + i + "' type='button' name='comprar' value='Comprar Pacote'>";
var pacoteSet3 = "</div>";
$("#pacotes").append(pacoteSet1 + "<h1>" + nomePacote + "</h1>" + "<h2>" + fornecedorPacote + "</h2>" + "<h3>" + precoPacote + "euros/mes </h3>" + pacoteSet2 + pacoteSet3);
$(document).find("#btnPac" + i).attr({
"idPacote": idPacote
});
}
}
});
});
And this is how I was trying to get their attributes
$("button").each(function () {
console.log(this.idPacote);
$.post("http://localhost:3000/pacote?id=" + this.idPacote);
});
But it doesn't seem to work
idPacote returns undefined and I have no idea why, because I simply give the buttons an "id" and replace the idPacote with the "id" itself, it will return the buttons ID
Sorry if the question sounds dumb. I am not very experienced in these matters.
When you are using jQuery I would suggest you to use the HTML5 data attribute in order to set a specified attribute to a HTML element:
<button data-id="1"></button>
You can set and access it using jQuery:
$('button').data('id', value); //set data-id
$('button').data('id'); //Read data-id
Furthermore change
<input id=btnPac" + i + "' type='button' name='comprar' value='Comprar Pacote'>
to
<button name='comprar'>Comprar Pacote</button>
in order to get elements from $('button')
I'm basically pulling info from itunes rss feeds to show the top songs based on which country is selected from the select element.
I was trying to replace the value from the option selected and insert it into the rss url to get that countrys top songs.The data pulls up fine however im
notable to choose any other options. japan is the only one that shows unless i change which option is first. How do i get the options to change the data shown?
// selects value for chosen country
var country;
//its selecting the value however its not refreshing.
country = $("#country :selected").text();
$.get('https://itunes.apple.com/' + country + '/rss/topsongs/limit=3/xml', function(data) {
var songArray = $(data).find('entry');
songArray.each(function() {
var title = $(this).find("title").text(); //grab song title
var artist = $(this).find("im\\:artist, artist").text(); //grab artist name
var album = $(this).find("im\\:name,name").text(); //grab album name
var image = $(this).find("im\\:image,image").eq(2).text(); //grab image link
var audioLink = $(this).find("link").eq(1).attr("href"); //grab music file
var audioDiv = $("source").attr("src", "audioLink"); //adds audio to source div
audioLink = '"' + audioLink + '"'
// youtube api to provide link to video based on the top songs populated
// Set the search term
var searchTerm = title;
var link;
var url = "https://www.googleapis.com/youtube/v3/search?q=" + searchTerm + "&part=snippet&maxResults=1&key=AIzaSyBvccDrp39n-InLrjDvv4PH_vfNbN0J_iE";
$.getJSON(url, function(data) {
var id = data.items[0].id.videoId;
link = "https://www.youtube.com/watch?v=" + id;
$("#song").append(
" <br><br>Song :" + title + "<br> Artist :" + artist + " <br>album: " + album + "<br>" + "<img src=" + image + "> " + "" + link + " <br>" + audioLink
);
});
}, "xml");
});
<select name="country" id="country">
<!-- <option>select song</option> -->
<option value="japan">jp</option>
<option value="spain">es</option>
<option value="france">fr</option>
</select>
<input type="button" id="button" value="get songs">
You need to get value or text of selected option
var country;
//its selecting the value however its not refreshing.
country= $("#country option:selected").text();
Or if you want value you can do this
country= $("#country").val();
You can use on change event
<select name="country" id="country">
<!-- <option>select song</option> -->
<option value="japan">jp</option>
<option value="spain">es</option>
<option value="france">fr</option>
</select>
$('#country').on('change', function() {
alert( this.value );
$.get('https://itunes.apple.com/' + this.value + '/rss/topsongs/limit=3/xml'
})
You will need to watch for the change event
$( "#country" ).change(function() {
country= $("#country").val();
$.get(....
});
I'm pretty new to javascript so please bear with me. I'm trying to create a drop down list of age choice from 1-100, with option 20 show as default. I also need to get the return value of the choice user selected so i can use to calculate the years. Here is the code i'm playing around with so far.
function createAgeList()
{
var myAgeOptions;
for (cntr=1; cntr<100; cntr++)
{
myAgeOptions = myAgeOptions + "<option value=" + cntr + ">" + cntr + "</option>";
}
var myAgeSelect = document.getElementById('agelist');
myAgeSelect.innerHTML = myAgeOptions;
}
HTML code:
<form name="yearsleptform" id="yearsleptform" method="post">
<select size="1" id="agelist" name="agelist">
</select>
</form>
document.yearsleptform.agelist.value
This is going to return you the value they have selected.
To set the default option:
function createAgeList()
{
var myAgeOptions;
for (cntr=1; cntr<100; cntr++)
{
myAgeOptions = myAgeOptions + "<option value=" + cntr + " "+(cntr===20?"selected=selected":"")+ ">" + cntr + "</option>";
}
var myAgeSelect = document.getElementById('agelist');
Live Demo
myAgeSelect.innerHTML = myAgeOptions;
}
to get the selected value:
document.yearsleptform.agelist.value
Live Demo
Say I have a ListBox populated with a name value pair SelectList(myUsers, "Key", "Value"):
#Html.ListBox("ListReviewers", (SelectList)ViewBag.ListOFReviewers, new { style = "width:120px;" })
I want to double click an option in this ListBox, and place it in a SelectionList like below:
<div class="selectedEmployees">
<select class="selectionList" multiple="multiple" name="AssignedReviewer" style="width:120px;">
<!--x.UserID, x.FirstName + " " + x.LastName) -->
<option value=""></option>
</select>
</div>
Once this collection is placed in the above, I want to store all the values in another SelectionList Collection for later use.
Here is the start of my jQuery code:
<script type="text/javascript">
$('#ListReviewers').dblclick(function (i, selected) {
//double click on this value of listbox of type SelectList(myUsers, "Key", "Value")
//store this value and text
var value = $(this).val;
//var empName = $(this).data[0];
var empName = $(selected).text();
alert(empName);
//append an option element <option value=""></option>
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
I can get the value of the dblclicked collection object, but not the text of the collection object. Is there a better way to do this?
Try attaching your event to the option within the select itself. You can then use this to access it's properties.
$('#ListReviewers option').dblclick(function () {
var value = $(this).val();
var empName = $(this).text();
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
Alternatively, you can use clone() and append() to move the option from one select to the other. This will save you having to worry about duplicate options being appended.
$('#ListReviewers option').dblclick(function () {
var $newOptions = $(this).clone(false);
$(this).remove();
$('.selectionList').append($newOption);
});