Increase number on button click - javascript

I'm trying to make an application with JSON data for a frisbee tournament. I'm now working on a page where you can view and edit the scores from a match. It should be possible to increase or decrease the score of either of the two teams. It looks like this:
I skipped some parts from the code to make it easier to read. This is the relevant code:
gamePage: function(data){
var score1 = parseInt(data.team_1_score),
score2 = parseInt(data.team_2_score);
var html = '',
html_pool_open = '<section class="new_page">';
html = html + html_pool_open;
var html_pool_top = '<div class="game">';
html = html + html_pool_top;
var html_team_1 = '<div class="name">'+data.team_1.name+'</div>'
+ '<div class="score score_team1">'
+ '<a href="#" onclick="" ><img src="/images/plus.png"/></a>'
+ '<span>'+score1+'</span>'
+ '<img src="/images/minus.png"/>'
+ '</div></div>';
The score between the span must be increased or decreased onclick
html = html + html_team_1;
x$('#content').html(html);
}
I'm not allowed to do it with jQuery, so vanilla JavaScript only please.

I would do somethig like this:
LIVE DEMO
var data = {
team_1_score: 42,
team_2_score: 6,
team_1 : {name:'Beast Amsterdam'},
team_2 : {name:'Amsterdam Money Gang'}
};
var SCORE_APP = {
tools : {
setScore : function( i, pm ){
var currScore= parseInt( data['team_'+ i +'_score'] , 10);
if(currScore=='0' && pm=='dn') return; // prevent -1 score
var newScore = data['team_'+ i +'_score'] += (pm=='up'? 1 : -1);
document.getElementById('team_'+ i +'_score').innerHTML = newScore;
}
},
game : {
gamePage : function(data) {
var html = '<section class="new_page">';
for(var i=1; i<3; i++){
html += '<div class="game"><div class="name">'+ data['team_'+i].name +'</div>'+
'<div class="score score_team1">'+
'<a href="javascript:;" onclick="SCORE_APP.tools.setScore(\''+i+'\',\'up\')">'+
'<img src="http://i.imgur.com/axk6J7M.jpg"/></a>'+
'<span id="team_'+i+'_score">'+ data['team_'+i+'_score'] +'</span>'+
'<a href="javascript:;" onclick="SCORE_APP.tools.setScore(\''+i+'\',\'dn\')">'+
'<img src="http://i.imgur.com/movjGkd.jpg"/></a>'+
'</div></div>';
}
html += '</section>';
document.getElementById('content').innerHTML = html;
}
},
init : function(){
this.game.gamePage(data);
}
};
SCORE_APP.init();
Add an ID to the span holding the score, and onclick send to the method setScore two arguments:
the team number (i = 1||2)
and the type of math we need to apply to the current score (I used a string representation "up" and "dn").
This two arguments are all you need to immediately keep up to date the data Object (holding the game stats) and apply the changes on screen to the targeted SPAN ID.

Set the onclick attribute within the <a href="#" onclick="" ></a> tag to calling a function such as increaseScore:
onclick="increaseScore()"
And give the span element an id:
<span id="myScore">
Then write a function which adds the score:
function increaseScore()
{
score1++;
document.getElementById("myScore").innerHTML=score1;
}

Related

How can I make this click counter work properly?

I'm making a Marvel API project. I added a Like button so it could count the likes, but everytime I click any like button the only counter adding numbers is the first one. Can anyone tell me how I do this properly?
The problem is because the ID is being made by a for, so how could I solve this?
This is my JS code (on the js file of my project) :
success: function(data)
{
footer.innerHTML = data.attributionHTML;
var string = "";
string += "<div class='row'>";
for (var i = 0; i < data.data.results.length; i++)
{
var element = data.data.results[i];
string += '<div class="col-md-3" align="center">';
string += "<img src='" + element.thumbnail.path + "/portrait_fantastic." + element.thumbnail.extension + "'/>";
string += '<button class="btn btn-success" onClick="testo()"><i class="fas fa-thumbs-up"></i> | <a id="likes">0</a></button>';
string += "<h3>" + element.title + "</h3>";
string += "</div>";
if ((i + 1) % 4 == 0)
{
string += "</div>";
string += "<div class='row'>";
}
}
marvelContainer.innerHTML = string;
}
And this is my onclick function (It is on my html file because it wont work on my js file)
<script>
var likes=0;
function testo()
{
likes += 1;
document.getElementById("likes").innerHTML = likes;
}
</script>
That is because all your buttons are being generated with the same id="likes" and then you are changing the HTML with document.getElementById("likes").innerHTML = likes;
for your code to work properly you will need to use a different approach, maybe adding a data-* attribute to your buttons and then change the likes by the data-* atribute using .getAttribute('data-id-something').innerHTML instead of document.getElementById("likes").innerHTML.
Or even better in this case you can give the buttons a class name and handle it with: document.getElementsByClassName("like-btn")
You can check the last option in this example:
var init = function(data){
var string ="";
string += "<div class='row'>";
for(var i = 0; i<4; i++)
{
// var element = data.data.results[i];
string += '<div class="col-md-3" align="center">';
string += "<img src='/portrait_fantastic.jgeg'/>";
string += '<button class="btn btn-success" onClick="testo('+i+')"><i class="fas fa-thumbs-up"></i> | <span class="like-btn">0</span></button>';
string += "<h3>Element title</h3>";
string += "</div>";
if((i+1) % 4 ==0)
{
string += "</div>";
string += "<div class='row'>";
}
}
document.getElementById("marvelContainer").innerHTML = string;
}
init();
<script>
var likes=0;
function testo(id) {
var btn = document.getElementsByClassName("like-btn");
likes = parseFloat(btn[id].innerHTML);
likes += 1;
btn[id].innerHTML = likes;
}
</script>
<div id="marvelContainer"></div>
I hope it will help you...
Gave the buttons a class, as that is what is going to be clicked.
Changed the link element to a span. Having a link in a button doesn't make much sense, as you can't "not" click the button and click the link.
Removed the inline onclick for the link and added an event listener logically on all the buttons.
The click logic finds the nested span in the button
It takes the data attribute on the span, turns it into an integer, and increments it
It then updates the data attribute value for the next click
And finally it updates the visible text that the user can see
EDIT
Changed it to bind the click event listener on the span as well and stop propagation on the click event. Actually clicking the span was causing the click event to register for the span, and not the button.
// fake out some data for the element generation
var data = { data: {
results: [
{ thumbnail: { path: '/path1', extension: 'jpg', title: 'Element1' } }
,{ thumbnail: { path: '/path2', extension: 'png', title: 'Element2' } }
,{ thumbnail: { path: '/path3', extension: 'gif', title: 'Element3' } }
]
} };
// fake out the container the elements are built to
var marvelContainer = document.querySelector('#container');
var string = "<div class='row'>";
for (var i = 0; i < data.data.results.length; i++) {
var element = data.data.results[i];
string += '<div class="col-md-3" align="center">';
string += "<img src='" + element.thumbnail.path + "/portrait_fantastic." + element.thumbnail.extension + "'/>";
// put a class on the button
// also removed the id and inline onclick
// change the id on the link to a class
// also initialized the data-likes on the link to zero
string += '<button class="btn btn-success likes-button"><i class="fas fa-thumbs-up"></i> | <span class="likes" data-likes="0">0</span></button>';
string += "<h3>" + element.title + "</h3>";
string += "</div>";
if ((i + 1) % 4 == 0) {
string += "</div>";
string += "<div class='row'>";
}
}
marvelContainer.innerHTML = string;
document.querySelectorAll('.likes-button, .likes').forEach(function(likeButton){
likeButton.addEventListener('click', incrementLikes);
});
function incrementLikes (e) {
e.stopPropagation();
// find the inner likes element of the button
var likes = e.target.querySelector('.likes') || e.target;
// increment the likes
var incrementedLikes = parseInt(likes.dataset.likes) + 1;
// update the data attribute for next click, and update the text
likes.dataset.likes = incrementedLikes.toString();
likes.innerText = incrementedLikes;
}
<div id="container">
</div>

How to add next previous buttons to popup?

I need to load XML data to next and previous buttons on the popup box. When button click, my code is fail to load the XML data. How can I implement the code.
Here is the script
function xmlParser(xml){
xml = $(xml).children();
$(xml).children().each(function () {
let tag = $(this).prop("tagName");
let image = '<img style="background-image:url(' + $(this).find("image").text() + ')"' + '" />';
let image2 = '<div><img src="' + $(this).find("image").text() + '" width="100%" alt="' + '" />' + '</div>';
let head = '<div>' + $(this).find("head").text() + '</div>';
let html = `<div class="col-sm-4 random" id="random">
<a href="#${tag}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>`;
let popup = `<div id="${tag}" class="overlay">
<div class="popup">
‹
›
<h6>${head}</h6>
<a class="close" href="#">×</a>
<div>${image2}</div>
</div>
</div>`;
$("#xmldata").append(html);
$("#popup").append(popup);
});
}
Plunker
Firstly div id is being duplicated if you use directly tag name. So use index in for loop and do some simple calculation to get prev & next items, something like:
$(xml).children().each(function (idx) {
let tag = $(this).prop("tagName");
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic rotation
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total -1) : prevIdx;
//..........check plunker code
http://next.plnkr.co/edit/Sj188FthvFu6H5uv?open=lib%2Fscript.js

print array of object in javascript and print in html tags

i am using storelocater.js for multiple location in google map and show the information according to the location with image. i can show only one image but i want to show multiple images inside the information panel. link this
Here is my code
var panelDiv = document.getElementById('panel');
storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">The nearest outlet:</li>';
var Store = storeLocator.Store;
Store.prototype.generateFieldsHTML_ = function(fields) {
var html = '';
html += '<div class="store-data">';
if(this.props_['title']){
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
}
html += '</div>';
return html;
}
var data = new storeLocator.StaticDataFeed;
data.setStores([
new storeLocator.Store('store02', new google.maps.LatLng(27.67663,85.31093), null, {images: ["img/thapathalil.jpg","img/thapathalil.jpg","img/thapathalil.jpg"]})
]);
and it shows:
Uncaught SyntaxError: Unexpected token for...
how can i solve this?? how can i fetch location inside of "images"
THANKS in advance
Actually you got Uncaught SyntaxError: Unexpected token for... because you used the for..loop in the string concatenation statement, directly after the + sign.
Change this code :
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
To the following:
html += '<div class="title"><div class="img-list clearfix">';
for (var i = 0; i <= this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
html += '<img src=' + this.props_['images'][i] + '>';
}
html += '</div></div>'
Note:
You should separate the concatenation of strings to the html
variable and the for loop logic, using html += instead of just using concatenation with + sign on multiple lines.
Make sure to wrap the properties names between two '' while accessing your objects, like in this.props_[images] where it should be this.props_['images'] and in this.props_[images[i]] where it should be this.props_['images'][i].
And the first 2 lines of your html variable decalaration and the concatenation, var html = ''; html += '<div class="store-data">'; can be shortened to just var html = '<div class="store-data">';.
I think there is a typo. Change this:
console.log(this.props_[images[i]])
to
console.log(this.props_['images'][i])
And you should use
i < this.props_['images'].length
So try this:
for (var i = 0; i < this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
}

JSON date not showing in HTML

I have a problem with JSON data: I want make news feed via JSON URL, but the information not showing in HTML.
$(function() {
var entries = [];
var dmJSON = "http://www.stellarbiotechnologies.com/media/press-releases/json";
$.getJSON( dmJSON, function(data) {
var html = '<div class="panel-body"><h3 class="lead">${title}</h3>';
html += '<time datetime="${published}">';
html += '<span class="glyphicon glyphicon-time"></span> ';
html += '<span class="month">${monthName}</span> ';
html += '<span class="day">${day}</span>, ';
html += '<span class="year">${year}</span></time></div>';
$('#ticker').html
},
<div id="ticker"></div>
You could do something like this:
<script>
$(document).ready(function() {
var dmJSON = "http://www.stellarbiotechnologies.com/media/press-releases/json";
$.getJSON( dmJSON, function(data) {
var html = '';
// loop through all the news items, and append the
// title and published date to the html variable.
for(var i = 0; i < data.news.length; i++){
html += '<div>';
html += data.news[i].title
html += '<br>';
html += data.news[i].published
html += '</div>';
}
// append all the html variable to the ticker div.
$("#ticker").append(html);
});
});
</script>
This will loop through the news node, and get the title and the published date and then append them to the page (an element with the id of ticker.

Passing value in HTML URL link

$.post("/diabetes/ropimages/getcount.php",{pid:$("#patient_id").val()} ,function(data1){
//alert(data1);
var count = data1;
var pid = $("#patient_id").val();
var rid;
for( var i = 1 ; i <= count ; i++) {
var link ='<img src="/diabetes/ropimages/thumbpicdisplay.php?pid=+pid+&rid=1" />';
$("#content1").empty().html(link);
}
});
I am trying to pass pid value in url ..but its taking directly as +pid+ as value ..how do i give it the value of pid.
And how do i print 3 images in a div? like the one in code
You simply need to terminate the string after ?pid= and then use the concatenation operator (+) to "insert" the pid variable in the appropriate location:
'<img src="/diabetes/ropimages/thumbpicdisplay.php?pid=' + pid + '&rid=1" />'
As for attaching the 3 images to the div, you might have more luck doing the following:
var link = '';
for(var i = 1; i <= count; i++) {
link += '<img src="...thumbpicdisplay.php?pid=' + pid + '&rid=1" />';
}
$("#content1").empty().html(link);

Categories