Addition of extract value from the string - javascript

I extracted value from the title as you can see. But I have problem with the addition. Basically I dont know how to add every .work-day-graph element in .ct-chart. So it will be like 1,25+8,25+0,75+0,5 = XY and 2,25+7,25+2,75+0,5 =XY. Any ideas ? Thanks a lot
DEMO: https://jsfiddle.net/1xn1eLfs/6/
JS:
$('.ct-chart').each(function() {
var graphTitle;
$(this).find('.work-day-graph').each(function() {
graphTitle = $(this).attr('title');
var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
//graphTimeVal = graphTime.parseInt();
$('<span class=output-val>' + graphTime + '</br>' + '</span>').appendTo('.output');
});
});

Here's a modified JsFiddle:
https://jsfiddle.net/3woe2cdq/4/
If you want to display the sum for both charts, you need a separate output inside both of them to make it work.
$('.ct-chart').each(function() {
var graphTitle;
// Save the sum of the hours
var graphTimeSum = 0;
$(this).find('.work-day-graph').each(function() {
graphTitle = $(this).attr('title');
var graphTime = graphTitle
.substring(graphTitle
.lastIndexOf('(') + 1, graphTitle
.lastIndexOf('h')
).replace(',', '.');
// Add the current hours to the sum
graphTimeSum += parseFloat(graphTime);
});
// Here we select the output class inside the chart
$('<span class=output-val>' + graphTimeSum + '</br>' + '</span>').appendTo($(this).find('.output'));
});

First, be carefull because you use "," and not "." in your string. To add those number, you must parseFloat on them.
Demo : https://jsfiddle.net/1xn1eLfs/6/
var val = 0;
$('.ct-chart').each(function() {
var graphTitle;
$(this).find('.work-day-graph').each(function() {
graphTitle = $(this).attr('title');
var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
graphTime = graphTime.replace(',', '.');
val += parseFloat(graphTime);
$('<span class=output-val>' + graphTime + '</br>' + '</span>').appendTo('.output');
});
});
console.log(val); // 23.5
Do the same but changing the second ct-chart class by ct-chart2 or whatever, so you can add element independently.

Related

Google Docs Apps Script getBackgroundColor(Offset)

Let's say I have some sentences in Google Docs. Just one sentences as an example:
"My house is on fire"
I actually changed the background color so that every verb is red and every noun blue.
Now I want to make a list with all the verbs and another one with the nouns. Unfortunately getBackgroundColor() only seems to work with paragraphs and not with single words.
My idea was, to do something like this (I didn't yet have the time to think about how to do the loop, but that's not the point here anyway):
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var colorVar = paragraphs[0].getText().match(/\w+/).getBackgroundColor(); // The regEx matches the first word. Next I want to get the background color.
Logger.log(colorVar);
}
The error message I get goes something like this:
"The function getBackgroundColor in the text object couldn't be found"
Thx for any help, or hints or comments!
You want to retrieve the text from a paragraph.
You want to retrieve each word and the background color of each word from the retrieved the text.
In this case, the color is the background color which is not getForegroundColor().
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
At first, the reason of your error is that getBackgroundColor() is the method of Class Text. In your script, getBackgroundColor() is used for the string value. By this, the error occurs.
In this answer, for achieving your goal, each character of the text retrieved from the paragraph is scanned, and each word and the background color of each word can be retrieved.
Sample script:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var textObj = paragraphs[0].editAsText();
var text = textObj.getText();
var res = [];
var temp = "";
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (c != " ") {
temp += c;
} else {
if (temp != "") res.push({text: temp, color: textObj.getBackgroundColor(i - 1)});
temp = "";
}
}
Logger.log(res) // result
}
When you run the script, the text of 1st paragraph is parsed. And you can see the result with res as an object.
In this sample script, the 1st paragraph is used as a test case. So if you want to retrieve the value from other paragraph, please modify the script.
References:
getBackgroundColor()
getBackgroundColor(offset)
editAsText()
If I misunderstood your question and this was not the direction you want, I apologize.
Here's a script your welcome to take a look at. It highlights text that a user selects...even individual letters. I did it several years ago just to learn more about how documents work.
function highLightCurrentSelection() {
var conclusionStyle = {};
conclusionStyle[DocumentApp.Attribute.BACKGROUND_COLOR]='#ffffff';
conclusionStyle[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
conclusionStyle[DocumentApp.Attribute.FONT_FAMILY]='Calibri';
conclusionStyle[DocumentApp.Attribute.FONT_SIZE]=20;
conclusionStyle[DocumentApp.Attribute.BOLD]=false;
conclusionStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]=DocumentApp.HorizontalAlignment.LEFT;
conclusionStyle[DocumentApp.Attribute.VERTICAL_ALIGNMENT]=DocumentApp.VerticalAlignment.BOTTOM;
conclusionStyle[DocumentApp.Attribute.LINE_SPACING]=1.5;
conclusionStyle[DocumentApp.Attribute.HEIGHT]=2;
conclusionStyle[DocumentApp.Attribute.LEFT_TO_RIGHT]=true;
var br = '<br />';
var selection = DocumentApp.getActiveDocument().getSelection();
var s='';
if(selection) {
s+=br + '<strong>Elements in Current Selection</strong>';
var selectedElements = selection.getRangeElements();
for(var i=0;i<selectedElements.length;i++) {
var selElem = selectedElements[i];
var el = selElem.getElement();
var isPartial = selElem.isPartial();
if(isPartial) {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:true selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor(selStart)=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(selStart, selEnd, bgcolor)
}else {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:false selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor()=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(bgcolor);
}
var elType=el.getType();
s+=br + 'selectedElement[' + i + '].getType()= ' + elType;
if(elType==DocumentApp.ElementType.TEXT) {
var txt = selElem.getElement().asText().getText().slice(selStart,selEnd+1);
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + 'Type:<strong>TEXT</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span>';
s+=br + 'Length: ' + txt.length;
s+=br + '<div id="sel' + Number(i) + '" style="display:none;">';
for(var key in elattrs)
{
s+= br + '<strong>' + key + '</strong>' + ' = ' + elattrs[key];
s+=br + '<input type="text" value="' + elattrs[key] + '" id="elattr' + key + Number(i) + '" />';
s+=br + '<input id="elattrbtn' + Number(i) + '" type="button" value="Save Changes" onClick="setSelectedElementAttribute(\'' + key + '\',' + i + ');" />'
}
s+='</div>Show/Hide';
}
}
if(elType==DocumentApp.ElementType.PARAGRAPH) {
var txt = selElem.getElement().asParagraph().getText();
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + '<strong>PARAGRAPH Attributes</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span> Text Length= ' + txt.length;
for(var key in elattrs)
{
s+= br + key + ' = ' + elattrs[key];
}
}
}
s+='<hr width="100%"/>';
}
//var finalP=DocumentApp.getActiveDocument().getBody().appendParagraph('Total Number of Elements: ' + Number(selectedElements.length));
//finalP.setAttributes(conclusionStyle);
}else {
s+= br + 'No Elements found in current selection';
}
s+='<input type="button" value="Toggle HighLight" onclick="google.script.run.highLightCurrentSelection();"/>';
//s+='<input type="button" value="Exit" onClick="google.script.host.close();" />';
DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('htmlToBody').append(s).setWidth(800).setHeight(450).setTitle('Selected Elements'));
}

Jquery click only works with double click

I am so close to getting this. Here's my code that is returning the correct url, but only when button is double-clicked. I only need one click to retrieve the image.
var origin = 'COMP';
var area = 'US';
var type = 'typeA';
var level = 'Xnay';
var time = '0';
var btn1 = document.getElementById("redbutton").winControl;
function change_area(new_area) {
area = new_area;
}
function change_type(new_type) {
type = new_type;
}
$(btn1).click(function () {
var src = "http://somesite.net/folder/WEB_" + origin + "_" + area + "_" + level + "_" + type + "_" + time + "HR.png";
change_area('GB');
change_type('typeB')
$('#mainmap').attr('src', src), false;
});
You try by adding
$(document).ready(function() { }); block
before the following line
$(btn1).click(function () {
Finally as,
$(document).ready(function() {
$(btn1).click(function () {
var src = "http://somesite.net/folder/WEB_" + origin + "_" + area + "_" + level + "_" + type + "_" + time + "HR.png";
change_area('GB');
change_type('typeB')
$('#mainmap').attr('src', src), false;
});
});

Hiding <p> field in javascript

Here's my code for gathering titles/posts from reddit's api:
$.getJSON("http://www.reddit.com/search.json?q=" + query + "&sort=" + val + "&t=" + time, function (data) {
var i = 0
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
i++
});
});
Basically every post (selftext) is assigned a different paragraph id (post0, post1, post2, etc) for every result that's pulled. I'm also going to create a "hide" button that follows the same id scheme based on my i variable (submit0, submit1, submit2, etc). I want to write a function so that based on which button they click, it will hide the corresponding paragraph. I've tried doing an if statement that's like if("#hide" + i) is clicked, then hide the corresponding paragraph, but obviously that + i doesn't work. How else can I tackle this?
Could you try something like the below?
showhide = $("<a class='hider'>Show/Hide</a>");
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
}
Alternatively:
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var showhide = $("<a class='hider" + i + "'>Show/Hide</a>");
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
});
i++
});

Add random class to an Appended div ? (jquery)

This is all of my code for the object I'm working with, but I'm thinking it's only the "create building in screen" part you really need to help me with.
My goal is to have it where instead of saying class="House houseRed", it says something like class="House +'randomClass'" etc, and that variable holds my other class names(i have 5 total).
It's for a mini-game I'm working on, and I need the buildings that spawn to have different looks, based on their class names.
//CREATE BUILDING IN MEMOMORY
function CreateHouseInMemory() {
//GET VALUES
var sAddress = $("#HouseAddress").val();
var sUniqueId = getUniqueId();
var iMaxResidents = $('input[name=housemaxresidents]').val();
var oHouse = {
sType: "House",
sAddress: sAddress,
sId: sUniqueId,
iMaxResidents: iMaxResidents,
Residents: aResidents = [],
babyInHouse: false
};
oCity.aBuildings.push(oHouse);
console.dir(oCity.aBuildings);
return oHouse;
}
//CREATE BUILDING IN SCREEN
function CreateHouseInScreen(oHouse)
{
$("#City").append('<div id="' + oHouse.sId + '" class="House houseRed" title="' + oHouse.sAddress + '"></div>');
$(".House").draggable();
$(".House").droppable();
}
;
//SPAWN BUILDING
$("#BtnCreateHouse").click(function() {
var oHouse = CreateHouseInMemory();
CreateHouseInScreen(oHouse);
});
Something like this
var classesnames = ['toto', 'titi', 'tata', 'tutu'],
classrandom = classesnames[Math.floor(Math.random() * classesnames.length)];
$("#City").append('<div id="' + oHouse.sId + '" class="House '+ classrandom +'" title="' + oHouse.sAddress + '"></div>');
Create an array of the target class names
var array = ['one', 'two','three','four', 'five'];
//then
var random = array[Math.floor(Math.random() * array.length)]
You can add a class randomly in a way like this:
function CreateHouseInScreen(oHouse)
{
var classes = ['houseRed', 'houseBlue', 'houseGreen'];
var randomIndex = Math.floor(Math.random() * classes.length);
var div = $('<div id="' + oHouse.sId + '" class="House" title="' + oHouse.sAddress + '"></div>');
div.addClass(classes[randomIndex]);
$("#City").append(div);
$(".House").draggable();
$(".House").droppable();
}
You could use something like
i = parseInt(Math.random() * 4)
to either generate an array index for an array of classes, e.g
classArray = ['class1', 'class2', 'class3', 'class4', 'class5']
obj.className = classArray[i]
or convert the integer to a string and append it to a constant string, e.g
obj.className = "myClass" + i.toString().

Code appending my img src

I'm wondering if someone can help me with trying to know why and possible solution to my error. I'm using JavaSript to load images, but when I test my page the src attribute is getting a / at the end of .jpg.
My console looks as follows:
loop: avatars/bugsbunnyundefined
loop: avatars/chimchim.jpg/
loop:avatars/christmastree.jpg/
loop: avatars/princess.jpg/
loop: avatars/squarepants.jpg/
loop: avatars/yosemite.jpg/
loop: avatars/wilma.jpg/
loop: avatars/coatandtie.jpg/
loop: avatars/lilymunster.jpg/
loop: avatars/georgejetson.jpg/
loop: avatars/tweety.jpg/
loop: avatars/cleveland.jpg/
//JavaScript OBJECT
var reviews = [
{ Id: "ajjhwejkssl",
Title: "The little camera that could!",
Rating: 5, Body: "text here",
CreateDate: new Date(2012,5,23,14,12,10,0),
Owner: {
Id: "kwergiueerwq",
Name: "Bugs Bunny",
Url: "./users.html?id=kwergiueerwq",
AvatarImage: "avatars/bugsbunny",
IsFeaturedReviewer: false,
CreateDate: new Date(2012,2,12,9,44,0,0)
}
}]
var data = reviews;
var newDiv = null;
var my_div = null;
var my_img = null;
var total = document.getElementById('total');
var review = $('#reviews');
$(document).ready(function(){
for (var i = 0; i < data.length; i++){
console.log("loop: " + data[i].Owner.AvatarImage + rand);
var rand = ".jpg/";
rand.replace(rand , ".jpg");
//CREATE NEW REVIEW DIV
var reviewPost = "<div class='review'><div class='clear'></div><div class='content'><div class='datePosted'>" + data[i].CreateDate + "</div><div class='avatar'><div class='header'><div class='rating'><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/></div></div><div class='clear'></div><div class='title'>" + data[i].Title + "</div><div class='memberImg'><img class='userImg' src=" + data[i].Owner.AvatarImage + '.jpg'+"/></div><div id='member'><div class='reviewedBy'>Reviewed by <a href='"+data[i].Owner.Url+"' class='member'>" + data[i].Owner.Name + "</a></div><div class='membership'>Member Since " + data[i].Owner.CreateDate + "</div></div></div></div><div class='clear'></div><div class='message'>" + data[i].Body + "</div></div><div class='clear'></div>";
//adds reviewPost inside of reviews
review.append(reviewPost);
$.each(".userImag" , function (){
//console.log("data: " + data[i].Owner.AvatarImage);
$(this).attr('src', data[i].Owner.AvatarImage + 'jpg');
});
}
});
I think the problem is in
var rand = ".jpg/";
rand.replace(rand , ".jpg");
the String.replace method just returns a changed string but do NOT change the original one.
String.replace
Description
This method does not change the String object it is called on. It simply returns a new string.
Take a look at this code:
console.log("loop: " + data[i].Owner.AvatarImage + rand);
var rand = ".jpg/";
rand.replace(rand , ".jpg");
The first line you're adding "+ rand" which rand has not be defined.
The second line you are setting the rand variable
And the third line is pretty much being ignored because no variable is being assigned to it. I don't think .jpg/ is actually in your image's source.
Josh
var rand = ".jpg/";
rand.replace(rand , ".jpg");
This doesnt make any sense at all. You are asigning a variable a value and replace that variable by itself ._0
You may want something like this:
var StringContainingFilePath;
var search = ".jpg/";
var replace = ".jpg";
StringContaingingFilePath = StringContaingingFilePath.replace(search,replace);

Categories