How to print out API info into HTML - javascript

This question regards a university homework project.
I need to print out in HTML some information about a public API. I have managed to call on the public API and print out the list of radio channels into the menu on the left (no click function added yet), but now I need to show the current schedule for the day for each channels. The schedule are supposed to show inside the html tag "info".
I'm struggling because of the API link in the tag scheduleurl. How can I show each channel's schedule for the day when I click on each channel in the menu?
Things to know: I'm not allowed to modify the HTML file. My own js code starting point is marked by a comment.
HTML code:
<!DOCTYPE html>
<html lang="se">
<head>
<title>Sveriges Radio</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Play:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/styles.css" type="text/css">
</head>
<body>
<header id="mainheader">
<div class="contain">
<h1 id="logo">DT084G - Projekt</h1>
<section id="player">
<select id="playchannel" class="form-control"></select>
<button id="playbutton" class="btn btn-primary">Spela</button>
</section>
<!-- /#search -->
</div>
<!-- /.contain -->
</header>
<div class="container">
<h2>SR - Sveriges Radio</h2>
<div class="left">
<section class="clist">
<h3>Bläddra via kanal</h3>
<nav id="mainnav">
<ul id="mainnavlist"></ul>
<div class="spacer" id="shownumrows">
<label for="numrows">Max antal: </label><input type="number" id="numrows" value="10" min="1" max="2000">
</div>
</nav>
</section>
<!-- /#lan -->
</div>
<!-- /.left -->
<div class="right">
<div id="info"></div>
<!-- /#info -->
</div>
<!-- /.right -->
<footer>
<p>Projektuppgift för kursen DT084G, Introduktion till programmering med JavaScript.</p>
<div id="radioplayer"></div>
</footer>
</div>
<!-- /.container -->
<script src="js/main.js"></script>
</body>
</html>
My so far written js code:
// Denna fil ska innehålla er lösning till projektuppgiften.
"use strict";
/* Delar till ej obligatorisk funktionalitet, som kan ge poäng för högre betyg
* Radera rader för funktioner du vill visa på webbsidan. */
//document.getElementById("player").style.display = "none"; // Radera denna rad för att visa musikspelare
//document.getElementById("shownumrows").style.display = "none"; // Radera denna rad för att visa antal träffar
/* Här under börjar du skriva din JavaScript-kod */
// HERE STARTS MY CODE
// variabler
var mainnavlistEl = document.getElementById("mainnavlist");
var i;
var restUrl = "http://api.sr.se/api/v2/channels/?format=json";
//funktion för ajax-anrop navigation vänster
window.onload = loadData;
function loadData() {
//ajax-antop
var xhr = new XMLHttpRequest();
xhr.onload = function () {
//check for answer
if (xhr.status === 200) {
var jsonStr = JSON.parse(xhr.responseText);
var channelsArr = jsonStr.channels;
//navigation vänster
// Inkluderat unika id och tagline för varje alternativ
for (i = 0; i < channelsArr.length; i++) {
// element
document.getElementById("mainnavlist").innerHTML += "<li id='" + channelsArr[i].id + "' title= '" + channelsArr[i].tagline + "'>" + channelsArr[i].name + "</li>";
}
console.log(channelsArr);
} else {
mainnavlistEl.innerHTML = "Fel vid anrop: " + xhr.status;
}
// Dropdown list
// Inkluderat unika id och tagline för varje alternativ
for (i = 0; i < channelsArr.length; i++) {
document.getElementById("playchannel").innerHTML += "<option id='" + channelsArr[i].id + "'" + "title='" + channelsArr[i].tagline + "'>" + channelsArr[i].name + "</option>";
}
}
//Send Ajax
xhr.open('GET', restUrl, true);
xhr.send(null);
}
// schedule
//variabel för id
document.getElementById("mainnavlist").addEventListener("click", function infoData(e){
var URL = "http://api.sr.se/api/v2/scheduledepisodes?channelid=" + e.target.id + "&format=json&indent=true";
//document.getElementById("info").innerHTML = URL ;
var idEl = document.getElementById("mainnavlist");
var restUrl2 = "http://api.sr.se/api/v2/scheduledepisodes";
var xhr = new XMLHttpRequest();
xhr.onclick = function () {
//check answer
if(xhr.status === 200) {
var jsonStr = JSON.parse(xhr.responseText);
var scheduleArr = jsonStr.title;
for(i = 0; i < scheduleArr.length; i++) {
document.getElementById("info").innerHTML += "<p>" + scheduleArr[i].title + "</p>";
}
}
}
xhr.open('GET', URL, true);
xhr.send(null);
})
Data inside the "scheduleurl tag in the channels json file
An example for one of the channels in the public API structure:
0: {image: "https://static-cdn.sr.se/sida/images/132/2186745_512_512.jpg?preset=api-default-square", imagetemplate: "https://static-cdn.sr.se/sida/images/132/2186745_512_512.jpg", color: "31a1bd", tagline: "Talat innehåll om samhälle, kultur och vetenskap. …ng och upplevelser till exempel i form av teater.", siteurl: "https://sverigesradio.se/p1", …}
1:
channeltype: "Rikskanal"
color: "ff5a00"
id: 163
image: "https://static-cdn.sr.se/sida/images/163/2186754_512_512.jpg?preset=api-default-square"
imagetemplate: "https://static-cdn.sr.se/sida/images/163/2186754_512_512.jpg"
liveaudio: {id: 163, url: "http://sverigesradio.se/topsy/direkt/srapi/163.mp3", statkey: "/app/direkt/p2[k(163)]"}
name: "P2"
scheduleurl: "http://api.sr.se/v2/scheduledepisodes?channelid=163"
siteurl: "https://sverigesradio.se/p2"
tagline: "P2 är den klassiska musikkanalen som även erbjuder jazz samt folk- och världsmusik. Digitalt sänder vi musikprogram dygnet runt, i FM finns även program på andra språk än svenska."
xmltvid: "p2.sr.se"
__proto__: Object

You are only getting the name. You need to get the other items and add the also. e.g. part of the code:
// On click pass id to the function
function myFunction(id) {
// put id in a variable
var id = id;
//use the variable in the url
var url = `http://example.com?id=id`;
// loop through elements for this id
for(var i=0; i<len; i++){
var id = response[i].id;
var slug = response[i].slug;
var excerpt = response[i].excerpt.rendered;
var link = response[i].link;
//put them all together in a variable in the html format you require
var tr_str =
'<td>'+
'<div class="card" style="width: 250px;">' +
'<div class="card-divider">' + id + ' ' + slug + '</div>' +
'<p>' + excerpt + '</p>' +
'<a href="' + link + ' " target="_blank">'+
'<input type="button" value="read more" style="margin-right: 15px;">' +
'</input>' +
' </a>' +
' </div>' +
'</div>'+
'</td>'
;
//append the variable to the dom element
document.getElementById("info").innerHTML += tr_str;

First off, I am not the best at either JavasSript or handling JSON, but maybe you could just consider me a rubber ducky of sorts, then it might lead you to a nice solution.
I went to the api url and looked at the data. It seems to me that the schedule portion of the json (hash, dictionary, what have you) is simply a link to THAT specific data... (which happens to be xml).
What I would do, if I were you, is before parsing the JSON into a string, I'd try to grab the schedule url, and and parse the xml into a useful format while parsing the JSON.
Once again, I'm not the best at this, but like rubber duckies, I do squeak. What do you think?

OK so I had to revise my answer, I think finally I understand what you want to do.
I'd replace for loop part of your code:
// create variable for the markup
let markup = '';
// using 'for of' loop for readibility
for (const channel of channelsArr) {
markup += `<li class="mainnavlist__item" id="${channel.id}">${channel.name}</li>`;
}
// once you have the whole markup constructed, replace the html content.
document.getElementById("mainnavlist").innerHTML(markup);
// now you would need an event listener, for example
document.addEventListener('click', function(event) {
if (event.target.classList.contains("mainnavlist__item")) {
// this function will render info html
showInfoData(event.target.id);
}
})
function showInfoData(id) {
// you need to gather the details you want to render into the info tag. This will give back the details of the clicked channel from the array, or here call another API, depends on from where you get the info
let currentChannel = channelsArr.filter(channel => channel.id === id)[0];
let infoMarkup = currentChannel.tagline;
document.getElementById("info").innerHTML(infoMarkup);
}
You also need to make sure to empty the info's innerHTML when you need to hide it (click outside, or on a close btn, etc). I hope I understood you right.

I had some trouble understanding what you want to achieve, but if it seems like you have made a successfull call to an API, and managed to display the names of the radiostation(?) in a list. What you want to do next i to be able to click on the items in the list on the left side, and then display some information on the right side?
The information you want to display should come from a API call to e.g:
"http://api.sr.se/v2/scheduledepisodes?channelid=163"
Now, what you are struggling with is how you can do this, and how to specify which ID to use when you call the API?
You already have the different ID's (the radiostation ID that goes on the end of the scheduleUrl string) as you HTML id for your list elements, right?
What i would do it create a listener event on your list elements. This listener should make a XHR-request to the scheduleUrl. You can use the ID from the HTML list element that you click as argument for you API call.
function listener(event){
url = "http://api.sr.se/v2/scheduledepisodes?channelid=";
id = event.target.id;
new_url = url + id;
// Make a new XHR-request here
// and display the received infomration
// where you want
}
However, to make this work, there are a few changes you need to make to your code.
When creating your list-elements, you use 'innerHTML'. This is not the best choice.
You should rather create an HTML DOM object, and then append this element to the 'unordered-list' element.
https://www.w3schools.com/jsref/met_node_appendchild.asp
You can also set the id, and other attributed directly to this 'child element'.
https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
It is when you create the list-elements you should add the event listener.
https://www.w3schools.com/js/js_htmldom_eventlistener.asp
So, to summarize:
You should change how you create you list-elements
You should add an click-listener to the list elements
The click listener should make a XHR-request based on the list-elements id (which is the same as the radiochannel id)

Related

get certain cell data from datatable

I'm trying to get the data from a datatable. I know that i can use datatable.data() but my cells have html data inside so I get something like this:
0:
CIF: "<span class='text-success font-weight-bold'>B81692097</span>"
CODIGO CURSO: "<div class='d-flex justify-content-center'><i data-toggle='tooltip' data-type='CODIGO CURSO' data-placement='top' title='Rellenar celda' class='empty-cell editable-data material-icons text-info'>keyboard</i></div>"
CODIGO USUARIO: "12345678-A"
DT_RowId: "row_1"
EDITORIAL: "CONZEPTO"
FACTURABLE: "<i class='material-icons text-success'>check_circle</i>"
FECHA ACTIVACION: 43831
HORAS: 1
LICENCIA: "-"
NOMBRE CENTRO: "<span class='text-success font-weight-bold'>ACADEMIA LIDER SYSTEM S.L.</span>"
NOMBRE CURSO: "<div class='d-flex justify-content-center'><span data-type='NOMBRE CURSO' class='editable-data text-info font-weight-bold'>Marketing y cosas</div>"
NOMBRE USUARIO: "Jose Perez Perez"
PERFIL: "-"
PRECIO: 1
REFERENCIA: "<div class='d-flex justify-content-center'><i data-toggle='tooltip' data-type='REFERENCIA' data-placement='top' title='Rellenar celda' class='empty-cell editable-data material-icons text-info'>keyboard</i></div>"
URL: "<span class='text-success font-weight-bold'>campusonline.lidersystem.com</span>"
VALIDADO: "↵ <span class='d-none orderable-value'>2</span>↵ <i data-toggle='tooltip
And, for example, from CIF I want to get B81692097 instead of <span class='text-success font-weight-bold'>B81692097</span>
I know that I could make a function to get the specific data from every cell but I wonder if there is an easier way to do this, I have been searching in the docs but I couldnt find anything.
Is there any way to get this with the tools that datatable offers?
Thank you guys
Depending on what specific data you need, here are some examples in a stand-alone demo you can run for yourself.
This includes an example showing the removal of HTML tags from cell data.
The demo table:
To see the results, uncomment the relevant console.log() statement(s). The browser console (F12) will show the output:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Iterate Cells</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="demo" class="display dataTable cell-border" style="width:100%">
<thead>
<tr><th>Column One</th><th>Column Two</th></tr>
</thead>
<tbody>
<tr><td>alfa</td><td class="foo">bravo</td></tr>
<tr><td class="foo">charlie</td><td>delta</td></tr>
<tr><td>echo</td><td><b>foxtrot</b></td></tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#demo').DataTable({
"columns": [
null,
null
]
});
// iterate all cell data as a JavaScript array of arrays:
var allData = table.data();
for (var i = 0; i < allData.length; i++) {
var rowData = allData[i];
for (var j = 0; j < rowData.length; j++) {
//console.log("row " + (i+1) + " col " + (j+1) + ": " + rowData[j]);
}
}
// get only one cell - row 3 column 2:
var oneSelectedCell = table.cell(2, 1);
//console.log(oneSelectedCell.data());
// get one cell's <td> node - row 3 column 2:
var oneSelectedCell = table.cell(2, 1);
//console.log(oneSelectedCell.node());
// get some cells using a css class name:
var someSelectedCells = table.cells(".foo").data();
for (var i = 0; i < someSelectedCells.length; i++) {
//console.log(someSelectedCells[i]);
}
// get only one cell without the HTML tags - row 3 column 2:
var oneSelectedCell = table.cell(2, 1);
var node = oneSelectedCell.node();
//console.log(node.textContent);
});
</script>
</body>
The final example shown above...
var oneSelectedCell = table.cell(2, 1);
var node = oneSelectedCell.node();
console.log(node.textContent);
...will print "foxtrot", with the enclosing <b> tag removed.
EDIT:
I forgot one useful function: every(). For example:
// get all nodes using the 'every()' function:
table.cells().every( function () {
console.log(this.node().textContent);
} );
This will list all the table cells' text values (removing embedded HTML, such as the <b> tag).
You can use string manipulation with this matter. You just need to get the indexes between the span tag. indexOf will get the first occurance of a string then use it to get the string you need with substring.
I added +1 on the first index because the start index return the position before the character so plus 1 will do the trick to make it after "<".
var str = "<span class='text-success font-weight-bold'>B81692097</span>";
var res = str.substring(str.indexOf(">")+1, str.indexOf("</"));
document.getElementById("result").innerHTML = res;
<p id="result"></p>

JQuery - click event for specific text?

<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="data_generator.js"></script>
<title> Twiddler </title>
</head>
<body class='box'>
<body>
<div class='container'>
<h1 class='title'>My Twiddler</h1>
<div class='main'>
<h2>Tweet Feed</h2>
<p class='tweets'></p>
<p class='new'></p>
<button class='button'>New Tweets</button>
</div>
</div>
<script>
$(document).ready(function(){
var $body = $('.main');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<p></p>');
$tweet.text('#' + tweet.user + ': ' + tweet.message + tweet.created_at);
$tweet.appendTo('.tweets');
index -= 1;
}
//show new tweets using button
var $button = $('.button');
$button.click(function() {
//get random tweet
//streams.home is an array of all tweets of all users
var tweet = streams.home[Math.floor(Math.random() * streams.home.length)]
var $tweet = $('<p></p>');
$tweet.text('#' + tweet.user + ': ' + tweet.message + tweet.created_at);
$tweet.appendTo('.tweets');
})
//click on user to see tweet history
$body.click(function() {
})
//styling
$('.box').css("background-image", "url('https://www.rightmixmarketing.com/wp-content/uploads/2016/04/Twitter-Background.png')");
$('.title').css('font-size', '40px').css('text-align', 'center');
$('h2').css('text-align', 'center');
});
</script>
</body>
</body>
</div>
</html>
I'm making a twitter look a like. I am trying to show a users history by being able to click on the username and displaying all current tweets. How can I go about and do this? I have it set to click on the body of my text but obviously that is not the right way. How can I specifically target the username in this case? I attached a picture of my current html
How to register the event clicking just on 'username' part of the text?
Consider the following:
<p>
<a class='click-me' >Username</a>
There is a lot of text here.
There's some more text here. I want to be able to click ...
</p>
So you just need to wrap the username in an html element which has a certain class.
Then, you specify a listener for the click event on that class:
$('.click-me').on('click', function() {
//do something
});
Now, you probably need to know which username we're talking about and how to get the specific posts, for that there are other solutions. But this one answers your question in specific.

URL dynamically generated with jquery is partially duplicated

I'm trying to dynamically generate a list of news items in queries. The news is read from a .json file and the html code is generated accordingly.
Since it is a bilingual site (IT-EN) I divided all the pages (except the home pages) into two sub-folders, called it and en.
The link to the news page is generated dynamically by identifying the inserted language as the lang attribute in the tag of the page and adding "news #" suggested by the numerical index of the in the json.
When I go to the news page I use window.location.toString (). Split ('#') to split the url and then select the one that comes after #.
I managed to dynamically generate everything and it works 99% but the link has a duplicate language:
instead of /en/news# o /it/news# ottengo /it/it/news#.
I omit the extension as it is automatically inserted by .htaccess
I tried to eliminate the variables that contain the link and the language by writing everything directly but it didn't help.
function genera_elencoNews (objDati){
let lingua = $('html')[0].lang.toLowerCase();
let articolo = objDati.articoli;
articolo = articolo.reverse();
let article = '';
let link_img = '';
let link = '';
let foto = '';
let data_articolo = '';
let titolo = '';
let contenuto = '';
for (let i = 0; i < Object.keys(objDati.articoli).length; i++){
article = $('<article>').attr('class', 'box excerpt');
link_img = $('<a>').attr('class', 'image left').attr('href', lingua + '/news#' + articolo[i].newsId);
link = $('<a>').attr('href', lingua + '/news#' + articolo[i].newsId);
foto = $('<img>').attr('class', 'Miniatura').attr('src', '/img/news/'+ articolo[i].foto);
data_articolo = $('<span>').attr('class', 'date').html(articolo[i].data);
titolo = articolo[i].titolo;
contenuto = $('<p>').html(articolo[i].contenuto.substring (0, 200) + '...');
$(article)//Genitore. tutto il resto è inserito dentro <article>
.prepend(link_img.append(foto))// Inserisce link e dentro mette la foto <article> --> <a> --><img>
.append($('<div>') //<article> --> <div>
.append($('<header>')// <article> --> <div> --> <header>
.append(data_articolo)//<article> ---> <div> ---><header> ---><span>DATA
.append($('<h3>')
.append(link.html(titolo))))
.append(contenuto))
.appendTo('#ultimeNews');
}
}
I managed to solve the problem but I decided not to remove the question in case it could be useful to others.
link = $('<a>').attr('href', lingua + '/news#' + articolo[i].newsId);
The problem is in building the link. It works in the home because it is in the root and therefore the path became example.com/it/news#.
On the news archive page, as it is located in example.com/it the generated link is example.com/it/it/news#.
Now, after solving, I understand that the solution is simple but not trivial, especially for those who do not have much experience: start the path of the link from the root: instead of it/news# use /it/news#
I then modified the line of code by adding a slash (/):
link = $('<a>').attr('href', '/' + lingua + '/news#' + articolo[i].newsId);

Click Listener exercised on initilazion but not working

I am learning javaScript/jQuery and all I want to do is use a loop to put a few pictures on the screen and set a counter that increases each time, the picture is clicked.
From other stackoverflow questions, I learned that for dynamically added DOM-Elements I cannot use jQuery's .click() but should rather use .on('Click','selector','function'). But that doesn't fix it.
For me the code WITHIN the listner is excercised once (I.e. the counter for each dogs is set to 1) and then a click on a picture yields:
jquery.min.js:3 Uncaught TypeError: ((n.event.special[g.origType] || (intermediate value)).handle || g.handler).apply is not a function
at HTMLDivElement.dispatch (jquery.min.js:3)
at HTMLDivElement.r.handle (jquery.min.js:3)
Here is my code:
I am particularly interested in/referring to this part:
// add a click counter to the click-per-dog-array
// initialize array element
clicksPerDog[i] = 0;
idString = "#"+wugel;
// create listener
$('#dogsWrapper').on('click',idString,function(j,fidString){
console.log("the j passed to the function is: "+j.toString());
//increase click counter
clicksPerDog[j]++;
// update text
$(fidString).text('This dog has been clicked: '+clicksPerDog[j].toString()+" times.");
}(i,idString));
For those interested, here is the whole shebang:
/*
*
* Click counter practice
*
*/
// HTML bits and variables to reuse for each dog
var HTMLDogContainer= "<div id='%dogname%' class='dogcontainer'></div>";
var HTMLDogName = "<h1 >%dogname%</h1>";
var HTMLDogImage = '<img src="resources/%dogname%.jpg" alt="%dogname%" class="dogpic">';
var HTMLCounterText ='<div class="counterText" id="%idtext%"> This dog has not been clicked yet. Counter is %numberClick%.</div>';
var HTMLDogButton ='<button type="button" class="btn btn-primary">%dogname%</button>';
var dogNames = ["Bonzo","Fox","Jimbo","Larry","Mike"];
console.log("dogNames length is this: "+dogNames.length.toString());
var clicksPerDog = [];
var tmpDogContainer, tmpDogName, tmpDogImage, tmpCounterText, tmpDogButton, tmpIdString;
// Let's loop over the dogs in our array and create the elements
for (var i = 0; i < dogNames.length; i++) { // The number, when thinking 1-indexed, we're on is simply i+1
// Create a div containing the whole shebang for each dogs
tmpDogContainer = HTMLDogContainer.replace('%dogname%', dogNames[i]);
tmpIdString = '#' + dogNames[i]; // Make it identifiable in this loop for jQuery ID Selector purposes
console.log('tmpIdString: ' + tmpIdString);
$('#dogsWrapper').append(tmpDogContainer); // append it to the DOM
// create content for the dog and append it to its respective wrapper
tmpDogName = HTMLDogName.replace('%dogname%', dogNames[i]); // header with dogname
$(tmpIdString).append(tmpDogName);
tmpDogImage = HTMLDogImage.replace('%dogname%', dogNames[i]); //image
$(tmpIdString).append(tmpDogImage);
tmpCounterText = HTMLCounterText.replace('%numberClick%', '0'); //counter
var wugel = dogNames[i].toString() + "counter";
tmpCounterText = tmpCounterText.replace('%idtext%', wugel); //counter
$(tmpIdString).append(tmpCounterText);
// create a button for the dog
tmpDogButton = HTMLDogButton.replace('%dogname%', dogNames[i]);
$('#dogSelector').append(tmpDogButton); // append it to the DOM
// add a click counter to the click-per-dog-array
// initialize array element
clicksPerDog[i] = 0;
idString = "#"+wugel;
// create listener
$('#dogsWrapper').on('click',idString,function(j,fidString){
console.log("the j passed to the function is: "+j.toString());
//increase click counter
clicksPerDog[j]++;
// update text
$(fidString).text('This dog has been clicked: '+clicksPerDog[j].toString()+" times.");
}(i,idString));
}
For this HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Doggo</title>
<!-- Latest compiled and minified Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- My own CSS -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div id="dogsWrapper">
</div>
<div class="dog-selection-area">
<p>Select the dog you would like to click:</p>
<div id="dogSelector" class="btn-group">
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="js/skript.js"></script>
</body>
</html>
Take a look at this sample implementation.
Clicking on "This dog has not been clicked yet.", increases the click count.
Treat it as a direction to proceed further with your changes.
Few things to note:
You hadn't wrapped your code in $(document).ready.
Since you need a counter for each dog, you may need an object for which dog name will be the key and the click count as the value.
I have corrected the code for this sample.
$(document).ready(function () {
// HTML bits and variables to reuse for each dog
var HTMLDogContainer = "<div id='%dogname%' class='dogcontainer'></div>";
var HTMLDogName = "<h1 >%dogname%</h1>";
var HTMLDogImage = '<img src="resources/%dogname%.jpg" alt="%dogname%" class="dogpic">';
var HTMLCounterText = '<div class="counterText" id="%idtext%"> This dog has not been clicked yet. Counter is %numberClick%.</div>';
var HTMLDogButton = '<button type="button" class="btn btn-primary">%dogname%</button>';
var dogNames = ["Bonzo", "Fox", "Jimbo", "Larry", "Mike"];
//console.log("dogNames length is this: " + dogNames.length.toString());
//var clicksPerDog = [];
var tmpDogContainer, tmpDogName, tmpDogImage, tmpCounterText, tmpDogButton, tmpIdString;
// Let's loop over the dogs in our array and create the elements
for (var i = 0; i < dogNames.length; i++) { // The number, when thinking 1-indexed, we're on is simply i+1
// Create a div containing the whole shebang for each dogs
tmpDogContainer = HTMLDogContainer.replace('%dogname%', dogNames[i]);
tmpIdString = '#' + dogNames[i]; // Make it identifiable in this loop for jQuery ID Selector purposes
//console.log('tmpIdString: ' + tmpIdString);
$('#dogsWrapper').append(tmpDogContainer); // append it to the DOM
// create content for the dog and append it to its respective wrapper
tmpDogName = HTMLDogName.replace('%dogname%', dogNames[i]); // header with dogname
$(tmpIdString).append(tmpDogName);
tmpDogImage = HTMLDogImage.replace('%dogname%', dogNames[i]); //image
$(tmpIdString).append(tmpDogImage);
tmpCounterText = HTMLCounterText.replace('%numberClick%', '0'); //counter
var wugel = dogNames[i].toString() + "counter";
tmpCounterText = tmpCounterText.replace('%idtext%', wugel); //counter
$(tmpIdString).append(tmpCounterText);
// create a button for the dog
tmpDogButton = HTMLDogButton.replace('%dogname%', dogNames[i]);
$('#dogSelector').append(tmpDogButton); // append it to the DOM
// add a click counter to the click-per-dog-array
// initialize array element
//idString = "#" + wugel;
// create listener
}
clicksPerDog = {
Bonzocounter: 0,
Foxcounter: 0,
Jimbocounter: 0,
Larrycounter: 0,
Mikecounter: 0
};
$('#dogsWrapper').on('click', function (e) {
var id = e.target.id;
if (id.indexOf('counter') >=0) {
clicksPerDog[id]++;
// update text
$('#' + id).text('This dog has been clicked: ' + clicksPerDog[id] + " times.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="dogsWrapper">
</div>
<div class="dog-selection-area">
<p>Select the dog you would like to click:</p>
<div id="dogSelector" class="btn-group">
Dog
</div>
</div>
</div>

Making table with objects in array?

I'm a beginner in javascript and I have a little problem with my code. I found an exercise and i'm trying to do it. I have to write a function that will insert text from variable into table. I never met something like this. This variable looks like four objects in array. I want to show text in the table when I press a button. There are two buttons. When I press "Fizyka" button i should see:
Fizyka
Ola Kowal
Ela Nowak
and when I press "Chemia":
Chemia
Ala Goral
Ula Szpak
So this is my code. All i can edit is function show(study):
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
</head>
<body>
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"></div>
<script>
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
if (study==='fizyka')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
if (study==='chemia')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
}
</script>
</body>
</html>
It's not working. I don't know how to insert text from this variable into table.
There is several problem with your code. I have written piece of code which is working and you can use it and inspire.
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"><h2></h2><ul></ul></div>
<script>
//Student array
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
console.log('ENTER show('+study+')');
//Select h2 element
var header = document.getElementById("list").firstChild;
//Set h2 element text
header.innerHTML = study;
//Select ul element
var list = document.getElementById("list").lastChild;
//Set inner html to empty string to clear the content
list.innerHTML = "";
//loop through students and set the appropriate html element values
for(var i = 0; i < student.length; i++){
//check whether student[i] studies study which is put as a paramter into the function
if(student[i].study === study){
//Create new li element
var li = document.createElement('li');
//Into li element add a new text node which contains all data about the student
li.appendChild(document.createTextNode(student[i].name + ' ' + student[i].second_name));
//add li element into ul
list.appendChild(li);
}
}
console.log('LEAVE show('+study+')');
}
</script>

Categories