toLocaleString() not working no errors showing up - javascript

I'm trying to add commas to the input to both the value integers and the summary number in the middle. I've added
$summaryNumber.toLocaleString();
but nothing works. I'm trying to understand what I'm doing wrong.
here's a fiddle with what I'm working with
https://jsfiddle.net/cmLkbq6e/2/
$(function(){
$("#doughnutChart").drawDoughnutChart([
{ title: "test", value : 150000000, color: "#e65c53" },
{ title: "test", value: 150000000, color: "#26a3b1" },
{ title: "test", value: 250000000, color: "#19818d" },
{ title: "test", value : 200000000, color: "#396b7e" },
{ title: "test", value : 100000000, color: "#a5a5a5" }
]);
});
those are the values I'm trying to target
and here's the summary number I'm trying to target
var $summaryTitle = $('<p class="' + settings.summaryTitleClass + '">' + settings.summaryTitle + '</p>').appendTo($summary);
var $summaryNumber = $('<p class="' + settings.summaryNumberClass + '"></p>').appendTo($summary).css({opacity: 0});
$summaryNumber.toLocaleString();

In the jsFiddle, find the below part of the code and change it,
Here is the updated JsFiddle : https://jsfiddle.net/cmLkbq6e/11/
Previously,
function drawDoughnutText(animationDecimal, segmentTotal) {
$summaryNumber
.css({opacity: animationDecimal})
.text((segmentTotal * animationDecimal).toFixed(1));
}
After Modification,
function drawDoughnutText(animationDecimal, segmentTotal) {
$summaryNumber
.css({opacity: animationDecimal})
.text((segmentTotal * animationDecimal).toLocaleString());
}

The problem is the$summaryNumber is object , it is not number
as I checked it in your code it be to
var $summaryNumber = $('<p class="' + settings.summaryNumberClass + '"></p>').appendTo($summary).css({opacity: 0});
which mean be an Object so your code is not working,
You should do something like:
afterDrawed : function() {
var number = parseFloat($('#doughnutChart .doughnutSummaryNumber').html());
$('#doughnutChart .doughnutSummaryNumber').html(number.toLocaleString());
},

Related

How to add open questions with textbox form Javascript

I am looking to change the following code that I have found and to add questions with textbook or box that the user can fill in the answer in stead of only multiple choice.
How ever, every time I am trying to add if or if else the code goes corrupt. I have copied the code and removed all but 3 questions. how can I modify this?
var quizzes = [
{
name: "test",
questions: [
{
text: "Test1?",
choices: [
{ text: "1", correct: false },
{ text: "2", correct: true },
{ text: "3", correct: false },
],
},
{
text: "test2",
choices: [
{ text: "4", correct: false },
{ text: "5", correct: false },
{ text: "6", correct: true },
],
},
{
text: "Test3",
choices: [
{ text: "7", correct: true },
{ text: "8", correct: false },
{ text: "9", correct: false },
],
},
{
]
// When the document is ready
window.addEventListener('DOMContentLoaded', function() {
var $container = document.getElementById('container');
// Initialize each quiz into the container
quizzes.forEach(function(quiz) { initQuiz(quiz, $container); });
});
function initQuiz(quiz, $container) {
// DOM elements
var $dom = initDOM(quiz, $container),
// Current question index (starts at 0)
num = 0,
score = 0;
nextScreen();
function nextScreen() {
if (num < quiz.questions.length) {
displayQuestion();
} else {
displayEndResult();
}
}
function displayQuestion() {
clearDisplayArea();
var question = quiz.questions[num];
// Display the image if there is one
if (question.image) {
$dom.display.innerHTML = '<img src="' + question.image + '" class="question-img"/>';
}
// Display the question
$dom.display.innerHTML +=
'<p>Q' + (num+1) + ': ' + question.text + '</p>'
+ question.choices.map(function(choice, i) {
return '<label>'
+ '<input type="radio" name="' + quiz.name + '" value="' + i + '"/>'
+ choice.text
+ '</label>';
return '<form>'
+ '<input type = "text" id="textbook" name="' + quiz.name + '" value="' + i + '"/>'
+ textbox.text
+ '</form>' ;
}).join('')
+ '<br>';
// Create Submit button
$submit = document.createElement('button');
$submit.addEventListener('click', onAnswerSubmit);
$submit.innerHTML = 'Submit';
// Add the submit button
$dom.display.appendChild($submit);
}
function onAnswerSubmit() {
// Get the checked radio button
var selectedChoice = $dom.display.querySelector('input:checked');
if (!selectedChoice) {
alert("You need to select an answer");
} else {
// If it's correct
if (quiz.questions[num].choices[selectedChoice.value].correct) {
score++; // Add 1 point to the score
}
num++;
nextScreen();
}
}
function displayEndResult() {
clearDisplayArea();
$dom.display.innerHTML = '<p>End of Quiz</p>'
+ '<p>Congratulations! Your score is: ' + score + '</p>'
+ '<p>If you scored lower than 2, please keep practicing</p>';
}
function clearDisplayArea() {
$dom.display.innerHTML = '';
}
// The "DOM" (Document Object Model) represents HTML elements
function initDOM(quiz, $container) {
// Create frame
So this is one solution, first make sure you have a input box in your html file.
Now with the input box you could give it a class of whatever you want as below
<input class="personAnswer"></input>
Now you could go back to your JS code and add the following
document.getElementById("personAnswer").(WHATEVER YOU WANT TO CHECK FOR)
And that's it!

How to set an element property from within a callback function

I have this "service" element where I would like to set the property "bookmarks" with the function getTree, which takes a callback function.
My problem is that I don't see how I could reach the property from within the callback function where "this" is undefined!!
<dom-module id="...">
<style>
:host {
display: none;
}
</style>
<script>
Polymer({
is: "bookmark-service",
properties: {
bookmarks: {
type: Array,
value: function() { return [{title:"init"}]; }
}
},
created: function() {
chrome.bookmarks.getTree(
function(bookmarkTreeNodes) {
this.bookmarks = bookmarkTreeNodes;
console.log(this.localName + '#' + this.id + ' in getTree.');
} );
console.log(this.localName + '#' + this.id + ' was created');
console.log("Bookmark: " + this.bookmarks[0].title + '.');
},
...
You could save a reference for this before calling getTree:
var that = this;
chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
that.bookmarks = bookmarkTreeNodes;
console.log(that.localName + '#' + that.id + ' in getTree.');
});
You can use bind to set this in your callback function.
chrome.bookmarks.getTree(
function(bookmarkTreeNodes) {
this.bookmarks = bookmarkTreeNodes;
console.log(this.localName + '#' + this.id + ' in getTree.');
}.bind(this) );
That was a part of my problem and I prefer not to use "bind" which I fear may have side effects with this and looks more complicated.
But another problem, was the asynchronous nature of getTree. For this, I had to add an observer.
Also, the properties doesn't even exist in "created" phase, I had to use "ready"
So here is the almost final result:
properties: {
bookmarks: {
type: Array,
value: function() { return [{title:"init"}]; },
observer: 'bookready'
}
},
bookready: function(){
console.log("Bookmark ready: " + this.bookmarks[0].title + '.');
},
ready: function() {
var self = this;
chrome.bookmarks.getTree(
function(bookmarkTreeNodes) {
self.bookmarks = bookmarkTreeNodes[0].children;
}
);
console.log(this.localName + '#' + this.id + ' was readied');
console.log("Bookmark: " + this.bookmarks[0].title + '.');
},

Don't know how to make a Dynamic jQuery CHART(flot : sin-cos)

So I am a junior and I am trying to understand how things work here.
I am using jquery.flot.js to make an interacting chart.
What I am trying to do?
I want to take this values (the values from the table) and make a chart:
#for((c,w)<- map){
<tr>
<td class="val">#c</td>
<td class="time">#w</td>
<br>
</tr>
}
I am using play framework and I get those values from my server through a map...
In #c I will get values that represents the humidity from an environment;
and
In #w I will get the timestamp from each value.
And this is the script for the chart :
$(function() {
var sin = [],
cos = [];
for (var i = 0; i < 14; i += 0.5) {
sin.push([i, Math.sin(i)]);
cos.push([i, Math.cos(i)]);
}
var plot = $.plot("#placeholder", [
{ data: sin, label: "sin(x)"},
{ data: cos, label: "cos(x)"}
], {
series: {
lines: {
show: true
},
points: {
show: true
}
},
grid: {
hoverable: true,
clickable: true
},
yaxis: {
min: -20,
max: 90
}
});
$("<div id='tooltip'></div>").css({
position: "absolute",
display: "none",
border: "1px solid #991F7A",
padding: "2px",
"background-color": "#E68AB8",
color : "#000",
opacity: 0.70
}).appendTo("body");
$("#placeholder").bind("plothover", function (event, pos, item) {
if ($("#enablePosition:checked").length > 0) {
var str = "(" + pos.x.toFixed(2) + ", " + pos.y.toFixed(2) + ")";
$("#hoverdata").text(str);
}
if ($("#enableTooltip:checked").length > 0) {
if (item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
$("#tooltip").html(item.series.label + " of " + x + " = " + y)
.css({top: item.pageY+5, left: item.pageX+5})
.fadeIn(200);
} else {
$("#tooltip").hide();
}
}
});
$("#placeholder").bind("plotclick", function (event, pos, item) {
if (item) {
$("#clickdata").text(" - click point " + item.dataIndex + " in " + item.series.label);
plot.highlight(item.series, item.datapoint);
}
});
// Add the Flot version string to the footer
$("#footer").prepend("Flot " + $.plot.version + " – ");
});
Maybe some of you played with this plug in, this is how things look :
I want to take the values from the time (#w) and put them on the axe : x , and the humidity (#c) on y ...
Can somebody help me please .... !?
Thank you.

Function added on link with jQuery

I am trying to create multiple html links to use as buttons. I am creating 15 at the moment, and in the future I might need to add more, so I want to do that through JS. The following code adds the objects on the screen, but the buttons don't do the function assigned. In fact, they don't do anything at all, they just go to index.html#.
function buttonCreate(){
var element = $(".left");
for (i in upgrades){
a = $('<a>',{
text: i,
href: '#',
id: i
});
var upgrade_button = $('#' + i);
upgrade_button.click(function(){upgrade(i);return false;});
a.addClass('myButton');
a.appendTo(element);
para = $('<p>',{
text: "",
id: i+"_upgrade"
});
para.appendTo(element);
para2 = $('<p>',{
text: "",
id: i+"_income"
});
para2.appendTo(element);
document.getElementById(i+"_upgrade").innerHTML = "You need " + Math.round(upgrades[i].cost).toLocaleString() + " to upgrade " + i;
document.getElementById(i+"_income").innerHTML = "Next " + i + " give " + Math.round(upgrades[i].income).toLocaleString() + " passive income";
}
}
I have also tried adding the function directly to the freshly created link element.
EDIT:
I am giving you the upgrades var and the upgrade function:
var upgrades = {
'A': {
cost: 100,
income: 10
},
'B': {
cost: 1000,
income: 100
},
'C': {
cost: 10000,
income: 1000
};
And the function:
function upgrade(type){
if ((points - upgrades[type].cost) >= 0) {
points -= upgrades[type].cost;
upgrades[type].cost *= upgrade_incr;
pincome += upgrades[type].income;
clearInterval(intervalVar);
intervalVar = setInterval(function(){pas_incr(pincome/8);},125);
//upgrades[type].income *= val_incr;
display = Math.round(points).toLocaleString();
document.getElementById("points").innerHTML = "Points: " + display;
document.getElementById(type+"_upgrade").innerHTML = "You need " + Math.round(upgrades[type].cost).toLocaleString() + " to upgrade " + type;
document.getElementById(type+"_income").innerHTML = "Each " + type +" gives " + Math.round(upgrades[type].income).toLocaleString() + " passive income";
document.getElementById("pincome").innerHTML = "You have " + Math.round(pincome).toLocaleString() + " passive income";
}
}
The fact that I am using both JS and Jquery is that I just learnt jquery, and started implementing that. As a note, I couldn't get it to work with simple JS either.
You are trying to query your button before inserting it into the DOM (upgrade_button). But you already have the button in your local scope (a). Simply add the click property during button creation.
Instead of:
a = $('<a>',{
text: i,
href: '#',
id: i
});
var upgrade_button = $('#' + i);
upgrade_button.click(function(){upgrade(i);return false;});
Try:
var a = $('<a>',{
text: i,
href: '#',
id: i,
click: function(){upgrade(i);return false;}
});
UPDATE
As TrueBlueAussie states in the comments, you cannot use i in your click closure because it will assume the final value of your for loop at the point in time when click is actually called.
New version:
var a = $('<a>',{
text: i,
href: '#',
id: i,
click: function(){ upgrade(this.id); return false; }
});
You're doing var upgrade_button = $('#' + i); before the element has been inserted into the DOM tree, so jQuery won't be able to look it up using the ID selector like that. Thus upgrade_button doesn't represent anything when you attach the click handler to it.
Also, upgrade_button will be identical to the a variable, so you can scrap it completely and just use a instead.

Make Javascript tooltip only display when I've specified the content

I'm using a small javascript to display a question mark icon with a explanatory tooltip next to product options on our ecommerce (bigcommerce) site. As it is, the script shows the icon for every product option, whether I've specified the content or not.
The content of the tooltip is set by using the following in the description section on the page:
<span id="[name of option]" style="display:none">[content of tooltip]</span>
If the content for the tooltip is not set, it displays "Description not available yet"
Here's an example of a page where the content is set:
http://www.www-savvyboater-com.mybigcommerce.com/carver-pontoon-bimini-top-sunbrella-a9sq4893ub
And here's an example of how it looks without the content set:
http://www.www-savvyboater-com.mybigcommerce.com/carver-bimini-top-double-duck-d5457ub
What I'd like is for the question mark icon to only show for the options where I've specified content for the tooltip. I don't know enough about javascript to figure it out on my own.
Here's the script in question:
$(document).ready(function() {
$(".productAttributeValue").each(function() {
var optionLabel = $(this).siblings('div');
var optionLabelText = optionLabel.children("label").children("span.name").text();
if ($("img", this).length < 1) {
$(this).siblings('div')
.children("label")
.children("span.name")
.append(" <div class='help_div' style='display: inline;'><img src='/product_images/uploaded_images/help.gif' alt='" + optionLabelText + "'/></div>");
}
});
$('.help_div').each(function() {
var slug = slugify($("img", this).prop('alt'));
var html = $("#" + slug).html();
var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"
if (!html) html = "Description not available yet."
$(this).qtip({
content: titleq + html,
position: {
corner: {
tooltip: 'topRight',
target: 'bottomLeft'
}
},
style: {
tip: {
corner: 'rightTop',
color: '#6699CC',
size: {
x: 15,
y: 9
}
},
background: '#6699CC',
color: '#FFFFFF',
border: {
color: '#6699CC',
}
}
});
});
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/^\s+|\s+$/g, "");
text = text.replace(/\s/gi, "-");
text = text.toLowerCase();
return text;
}
});
The best way to do this is to not create the HTML for the ? in the first place.
$(document).ready(function() {
$(".productAttributeValue").each(function() {
var optionLabel = $(this).siblings('div');
var optionLabelText = optionLabel.children("label").children("span.name").text();
// check that optionLabelText is not an empty string
if ($("img", this).length < 1 && slugify(optionLabelText).trim().length) {
$(this).siblings('div')
.children("label")
.children("span.name")
.append(" <div class='help_div' style='display: inline;'><img src='/product_images/uploaded_images/help.gif' alt='" + optionLabelText + "'/></div>");
}
});
$('.help_div').each(function() {
var slug = slugify($("img", this).prop('alt'));
var html = $("#" + slug).html();
var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"
if (!html) html = "Description not available yet."
$(this).qtip({
content: titleq + html,
position: {
corner: {
tooltip: 'topRight',
target: 'bottomLeft'
}
},
style: {
tip: {
corner: 'rightTop',
color: '#6699CC',
size: {
x: 15,
y: 9
}
},
background: '#6699CC',
color: '#FFFFFF',
border: {
color: '#6699CC',
}
}
});
});
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/^\s+|\s+$/g, "");
text = text.replace(/\s/gi, "-");
text = text.toLowerCase();
return text;
}
});
If that is not possible then there are two ways to handle this:
Hide the ? in CSS by default and then show them using javascript if data exists
.help_div {
display:none;
}
And in your javascript:
var slug = slugify($("img", this).prop('alt'));
var html = $("#" + slug).html();
var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"
if (html) {
$(this).show();
}
Have the ? visible by default but destroy them if no data is found:
In your javascript:
var slug = slugify($("img", this).prop('alt'));
var html = $("#" + slug).html();
var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"
if (!html) {
$(this).remove();
}
Option 1 has less chance of causing issues/being jarring but it's up to you how you would like to implement this.

Categories