Rewriting elements in html by innerHTML - javascript

i have a a code like that:
<p id = "outputLaps"></p>
JS:
document.getElementById("outputLaps").innerHTML = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds
and i don't want to rewrite it, but to display it under the previous "lap".
Thanks for answers :).

Use insertAdjacentHTML when you want to insert HTML.
var str = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds;
document.getElementById("outputLaps").insertAdjacentHTML("beforeend", str);
However, if you only want to insert text, you can append a text node:
var str = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds;
document.getElementById("outputLaps").appendChild(
document.createTextNode(str)
);
In case you want the text to go to the next line, you can either
Insert a newline character \n and style the paragraph with white-space set to pre, pre-wrap or pre-line.
Insert a <br /> HTML element.
Use different paragraphs. Seems the most semantic.

A better solution is to use <ol> or <ul id="outputLaps"> instead, and add <li>s to it.
var li = document.createElement( 'li' )
li.textContent = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds
document.getElementById( 'outputLaps' ).appendChild( li )
In this case, because .appendChild() returns the element being added, we can avoid the variable.
document.getElementById( 'outputLaps' )
.appendChild( document.createElement( 'li' ) )
.textContent = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds
Maybe you don't want the ugly bullets, so you can change them, or simply remove them with a CSS rule:
<style>
ul { list-style-type: none; }
</style>

You can use += to concatenate to the existing value.
document.getElementById("outputLaps").innerHTML += "<br>Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds
You can also use the insertAdjacentHTML() method, which doesn't modify the existing DOM nodes in the paragraph.
document.getElementById("outputLaps").insertAdjacentHTML('beforeend', "<br>Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds);

Related

Preserve Formatting When Setting New Cell Value (Google Spreadsheet)

I have the following script which sets a new value for a selected spreadsheet cell. It works as expected but after every entry it clears all the previous formatting from the cell. How can I modify the code to make sure it preserves all the partial formatting, such as font weight/color? Thank you for your help.
function enterName1(options1, activity1, number1) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var cell = sheet.getActiveCell();
var value = cell.getValue();
var formattedDate = Utilities.formatDate(new Date(), "GMT+3", "dd.MM.yy' at 'HH:mm");
Logger.log(formattedDate);
if (value === '') {
value = value + "📞 " + formattedDate + " call " + options1 + number1 + ": " + activity1;
sheet.getActiveRange().setNumberFormat('#STRING#');
cell.setValue(value);
} else {
value = value + "\n\n" + "📞 " + formattedDate + " call " + options1 + number1 + ": " + activity1;
sheet.getActiveRange().setNumberFormat('#STRING#');
cell.setValue(value);
}
}
I believe your goal as follows.
Question 1: You want to preserve the existing text styles of the text in the cell when the value is added to the cell including the values.
Question 2: You want to preserve the existing text styles of the text in the cell when the value is added to the cell including the values. And also, you want to set the text style for formattedDate of the adding text.- Question 3: You want to preserve the existing text styles of the text in the cell when the value is added to the cell including the values. And also, you want to set the text style for formattedDate of the adding text. And also, even when the cell is empty, you want to set the text style for formattedDate of the adding text.
Answer for question 1:
Modification points:
In this case, it is required to retrieve the text styles of the existing values and set the text styles after the value was added. "RichTextValue" is used for this.
When your script is modified, it becomes as follows.
Modified script:
From:
} else {
value = value + "\n\n" + "📞 " + formattedDate + " call " + options1 + number1 + ": " + activity1;
sheet.getActiveRange().setNumberFormat('#STRING#');
cell.setValue(value);
}
To:
} else {
value = value + "\n\n" + "📞 " + formattedDate + " call " + options1 + number1 + ": " + activity1;
var richTextValue = cell.getRichTextValue();
var existingStyles = richTextValue.getRuns().map(e => ({start: e.getStartIndex(), end: e.getEndIndex(), style: e.getTextStyle()}));
var richTexts = SpreadsheetApp.newRichTextValue().setText(value);
existingStyles.forEach(e => richTexts.setTextStyle(e.start, e.end, e.style));
cell.setRichTextValue(richTexts.build());
cell.setNumberFormat('#STRING#');
}
In this modified script, the text styles of the existing value are set. So the added text has no text style. Please be careful this.
Answer for question 2:
Modification points:
In this case, it is required to retrieve the text styles of the existing values and also set the text style for formattedDate, and then, set the text styles after the value was added. "RichTextValue" is also used for this.
When your script is modified, it becomes as follows.
Modified script:
From:
} else {
value = value + "\n\n" + "📞 " + formattedDate + " call " + options1 + number1 + ": " + activity1;
sheet.getActiveRange().setNumberFormat('#STRING#');
cell.setValue(value);
}
To:
} else {
var textStyle = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("#FF0000").build(); // Please set this for the additional text.
var richTextValue = cell.getRichTextValue();
var existingStyles = richTextValue.getRuns().map(e => ({start: e.getStartIndex(), end: e.getEndIndex(), style: e.getTextStyle()}));
var startOffset = (value + "\n\n" + "📞 ").length;
existingStyles.push({start: startOffset, end: startOffset + formattedDate.length, style: textStyle});
var richTexts = SpreadsheetApp.newRichTextValue().setText(value + "\n\n" + "到 " + formattedDate + " call " + options1 + number1 + ": " + activity1);
existingStyles.forEach(e => richTexts.setTextStyle(e.start, e.end, e.style));
cell.setRichTextValue(richTexts.build());
cell.setNumberFormat('#STRING#');
}
In this modified script, the text styles of the existing value and formattedDate of the adding text are set.
As above sample, formattedDate has the bold and red font color.
Answer for question 3:
Modification points:
In this case, it is required to retrieve the text styles of the existing values and also set the text style for formattedDate, and then, set the text styles after the value was added. "RichTextValue" is also used for this. And also, when the cell is empty, it is required to set the text style for formattedDate of the adding text.
When your script is modified, it becomes as follows.
Modified script:
From:
if (value === '') {
value = value + "📞 " + formattedDate + " call " + options1 + number1 + ": " + activity1;
sheet.getActiveRange().setNumberFormat('#STRING#');
cell.setValue(value);
} else {
value = value + "\n\n" + "📞 " + formattedDate + " call " + options1 + number1 + ": " + activity1;
sheet.getActiveRange().setNumberFormat('#STRING#');
cell.setValue(value);
}
To:
var textStyle = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("#FF0000").build(); // Please set this for the additional text.
if (value === '') {
value = "📞 " + formattedDate + " call " + options1 + number1 + ": " + activity1;
var richTexts = SpreadsheetApp
.newRichTextValue()
.setText("📞 " + formattedDate + " call " + options1 + number1 + ": " + activity1)
.setTextStyle(("📞 ").length, ("📞 " + formattedDate).length, textStyle);
cell.setRichTextValue(richTexts.build());
cell.setNumberFormat('#STRING#');
} else {
var richTextValue = cell.getRichTextValue();
var existingStyles = richTextValue.getRuns().map(e => ({start: e.getStartIndex(), end: e.getEndIndex(), style: e.getTextStyle()}));
var startOffset = (value + "\n\n" + "📞 ").length;
existingStyles.push({start: startOffset, end: startOffset + formattedDate.length, style: textStyle});
var richTexts = SpreadsheetApp.newRichTextValue().setText(value + "\n\n" + "到 " + formattedDate + " call " + options1 + number1 + ": " + activity1);
existingStyles.forEach(e => richTexts.setTextStyle(e.start, e.end, e.style));
cell.setRichTextValue(richTexts.build());
cell.setNumberFormat('#STRING#');
}
Reference:
Class RichTextValue

Attempting to output to a text box with Javascript

I'm creating a communications generator that will standardise SMS communications regarding critical IT incidents for my company. I've got an IF/ELSE statement that identifies whether an issue is new, updated, or resolved to pull the necessary information together and format it accordingly. As far as I can tell, everything here is fine, however I'm having an issue writing to a text box ('smsToSend') which should allow the user to review before they copy the text across to our sms sender app, as nothing is being output into this box.
function generateSMS(){
var issueTitle = document.getElementById("incidentTitle");
var advisorImpact = document.getElementById("advisorImpact";
var incidentUpdate = document.getElementById("incidentUpdate");
var incidentStatus = document.getElementById("incidentState");
var startTime = document.getElementById("startTime");
var endTime = document.getElementById("endTime");
var incidentPriority = document.getElementById("incidentPriority");
var incidentBrand = "TechTeam";
var systemImpacted = document.getElementById("systemImpacted");
var incidentReference = document.getElementById("incidentReference");
var smsToSend = document.getElementById("smsToSend");
if (incidentStatus != "Closed"){
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT RESOLVED: " + systemImpacted + ": " + incidentUpdate + ": Start: " + startTime + " End: " + endTime + " Reference: " + incidentReference;
}
else{
if (incidentUpdate == "We are investigating this issue"){
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT ISSUE: " + systemImpacted + ": " + issueTitle + ". " + advisorImpact + ": " + incidentReference;
}
else {
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT UPDATE: " + systemImpacted + ": " + incidentUpdate + ": " + incidentReference;
}
}
}
generateSMS();
alert.getElementById(smsToSend);
Try replacing all assignments to smsToSend like this:
smsToSend = yourValue;
With this:
smsToSend.value = yourValue;
Your problem happens because smsToSend is an instance of an element, rather than a variable linked to the displayed text. To update the element's value, you have to change the value property of the element.
The Right way of setting the value to a text box is
var smsToSend = document.getElementById("smsToSend");
smsToSend.value = "Your value";

creating a page based on a field

In my form I have a total field which is the sum of several checkboxes. When it reaches 21 total page one must be created. below the code, which worked well in another case and this time it gives me a syntax error. someone there you an idea ??
Thank you in advance
this.getField("TOTAL").value =
this.getField("P6eval_competences.manageriales.0").value +
this.getField("P6eval_competences.manageriales.1").value +
this.getField("P6eval_competences.manageriales.2").value +
this.getField("P6eval_competences.manageriales.3").value +
this.getField("P6eval_competences.manageriales.4").value +
this.getField("P6eval_competences.manageriales.5").value +
this.getField("P6eval_competences.manageriales.6").value +
this.getField("P6eval_competences.manageriales.7").value +
this.getField("P6eval_competences.manageriales.8").value +
this.getField("P6eval_competences.manageriales.9").value +
this.getField("P6eval_competences.manageriales.10").value +
this.getField("P6eval_competences.manageriales.11").value +
this.getField("P6eval_competences.manageriales.12").value +
this.getField("P6eval_competences.manageriales.13").value +
this.getField("P6eval_competences.manageriales.14").value +
this.getField("P6eval_competences.manageriales.15").value +
this.getField("P6eval_competences.manageriales.16").value +
this.getField("P6eval_competences.manageriales.17").value +
this.getField("P6eval_competences.manageriales.18").value +
this.getField("P6eval_competences.manageriales.19").value +
this.getField("P6eval_competences.manageriales.20").value +
this.getField("P6eval_competences.manageriales.21").value +
this.getField("P6eval_competences.manageriales.22").value +
this.getField("P6eval_competences.manageriales.23").value +
this.getField("P6eval_competences.manageriales.24").value +
this.getField("P6eval_competences.manageriales.25").value +
this.getField("P6eval_competences.manageriales.26").value +
this.getField("P6eval_competences.manageriales.27").value +
this.getField("P6eval_competences.manageriales.28").value +
this.getField("P6eval_competences.manageriales.29").value +
this.getField("P6eval_competences.manageriales.30").value +
this.getField("P6eval_competences.manageriales.31").value;
if (getField("TOTAL").value == "21") {
var expTplt = getTemplate("NIVEAU MATURE");
expTplt.spawn(numPages, true, false);
}
I think you should use parseInt() method cause the values which are returned are not Integer rather they are Strings.

Use variable name fadeIn and Prepend

I want to prepend this variable "logText" and make it fade in at the same time.
var logText = today + ":" + " " + document.getElementById("textBox").value + '<br>\n';
$("#logContent").prepend(logText);
Here is what I got but it doesn't work.
var logText = today + ":" + " " + document.getElementById("textBox").value + '<br>\n';
$("#logContent").prepend($(logText).fadeIn('slow'));
$("<p>" + today + ": " + $("#textBox").val() + "</p>") // new DOM Node
.css("display", "none") // hide it
.prependTo("#logContent") // prepend it to #logContent
.fadeIn("slow"); // fade it in slowly
fiddle
$("#logContent").prepend(today + ": " + $("#textBox").val() + '<br>').fadeIn('slow');

Integrating a simple html table into javascript

I am being asked to create a table using javascript that displays simple arithmetic of a variable given to me by the user and I'm sure that my syntax is off inside of my document.write, but I'm not sure where and how. My error console says I'm missing a closing ')' at line 18 the end which is not true at all. I saw that in other cases it is frowned upon to use the document.write function for this purpose, but it's explicitly stated that I should do so as part of the requirements for the completion of this lab, so my sincere apologies for this transgression beforehand.
The code is below - Thanks in advance for any and all help:
<script>
var e1="", e2="", e3="", e4="", e5="", e6="", e7="", e8="", e9="";
e1 = prompt("Enter your first name in lower case", "");
var e1u = substr(0, 1);
e1 = e1u.toUpperCase() + e1.substr(1, e1.length-1);
e2 = prompt(e1 + ", enter an integer from 1 to 9", "");
e3 = prompt("Now enter 5 numbers delineated by a comma!", "");
e4 = prompt("Now enter 3 colors delineated by a comma!");
e5 = new date();
e6 = e3.split(',');
e7 = e4.split(',');
document.write(""Today's Date = " + e5.getMonth()+1 + "/" + e5.getDay() +
"/" + e5.getFullYear() + "\n" + "The number in e2 is " + e2 + "\n"
+ "<table><caption>Times Table for the number + e2 + "</caption>"");
for(var i=0; i<13; i++)
{
document.write(""<tr>""<td>" + e2 + "</td>" + "<td>" + i + "</td>" + "<td>" + "=" + "</td>" + "<td>" + (e2 * 1) * i + "</td>""</tr>"");
}
</script>
I fixed the following for you:
document.write("Today's Date = " + e5.getMonth()+1 + "/" + e5.getDay() +
"/" + e5.getFullYear() + "\n" + "The number in e2 is " + e2 + "\n"
+ "<table><caption>Times Table for the number" + e2 + "</caption>");
and
document.write("<tr><td>" + e2 + "</td>" + "<td>" + i + "</td>" + "<td>" + "=" + "</td>" + "<td>" + (e2 * 1) * i + "</td></tr>");
Don't double up quotations, and use an editor with syntax high-lighting. It will save you a lot of time.
This looks wrong:
+ "</td>""</tr>""
maybe you want
+ "</td></tr>"
Date(), not date()
e1.substr, not just substr and I would use substring, not substr
Missing quote after number e2
I would do it like this
http://jsfiddle.net/mplungjan/eggWj/
Tables must have the following nesting structure:
<table>
<tr>
<td> ... </td>
</tr>
</table>
Your <caption> cannot be placed where it is and likely belongs in a TD or outside of the table completely.

Categories

Resources