I've successfully made a random sentence generator based on the values of an object in an array that works based on a click of a button. What I can't figure out is how to create a new sentence with each click of the button.
It seems like I could just clear out the contents of #output when the button is clicked and randomWord() would just run again but no dice.
var words = {
noun : ['mouse','bird','cat','dog'],
verb : ['runs','sleeps','explodes','flies'],
place : ['house', 'space station', 'car', 'office']
};
var container = document.getElementById('output');
function print(sentence){
container.innerHTML = sentence;
}
var noun;
var verb;
var place;
var word;
var sentence;
var button;
function randomWord( type ){
rando = Math.floor(Math.random() * words[type].length);
word = words[type][rando];
return word;
}
noun = randomWord('noun');
verb = randomWord('verb');
place = randomWord('place');
$('button').click(function(){
$('#output ').empty();
var sentence = "<p>The " + noun + " " + verb + " in the " + place + ".</p>";
print(sentence);
});
Codepen
You need to update your randomised variables each time you click the button, currently you're doing it once during script initialisation:
$('button').click(function(){
$('#output ').empty();
//generate new random words on click
noun = randomWord('noun');
verb = randomWord('verb');
place = randomWord('place');
var sentence = "<p>The " + noun + " " + verb + " in the " + place + ".</p>";
print(sentence);
});
A couple of things:
id reference to output has an extra space
$('#output ').empty() ===> $('#output').empty();
You may want to use Document Ready from jQuery
And like the other answers stated, you need the random calls in the clickable action
Quick test here:
<html>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" ></script>
<script>
$( document ).ready(function() {
var words = {
noun : ['mouse','bird','cat','dog'],
verb : ['runs','sleeps','explodes','flies'],
place : ['house', 'space station', 'car', 'office']
};
var container = document.getElementById('output');
function print(sentence){
container.innerHTML = sentence;
}
var noun;
var verb;
var place;
var word;
var sentence;
var button;
function randomWord( type ){
rando = Math.floor(Math.random() * words[type].length);
word = words[type][rando];
return word;
}
$('#button').click(function(){
noun = randomWord('noun');
verb = randomWord('verb');
place = randomWord('place');
$('#output').empty();
var sentence = "<p>The " + noun + " " + verb + " in the " + place + ". </p>";
print(sentence);
});
});
</script>
<div id="output"></div>
<button id="button">click</button>
</html>
Maybe you just have to try:
$('button').click(function(){
noun = randomWord('noun');
verb = randomWord('verb');
place = randomWord('place');
var sentence = "<p>The " + noun + " " + verb + " in the " + place + ".</p>";
print(sentence);
});
Related
I am doing a madlibs-type program. Prompts ask for words, which are then added to a string. I would like the words used from the prompts to be underlined when they are displayed with the rest of the string. I have created an array with all the prompts. Now, I just need to know how to run through that array and change the text-decoration to "underline". I know I need to use a for-loop through the array, but not sure of how to approach it.
What is the best way to make this happen?
HTML:
<body>
<div id = "story-space">
</div>
<script src = "madlibs.js"></script>
</body>
JS:
var prompt1 = prompt("Enter a animal.");
var prompt2 = prompt("Enter a city.");
var prompt3 = prompt("Enter an activity.");
var prompts = [prompt1, prompt2, prompt3, prompt4];
var text = "There was once was a " + prompt1 + " from " + prompt2 + " who liked to " + prompt3 + "."
document.getElementById("story-space").innerHTML = text;
Why can you add the html style like this
var text = "There was once was a <span style='text-decoration:underline'>" + prompt1 + "</span> from <span style='text-decoration:underline'>" + prompt2 + "</span> who liked to <span style='text-decoration:underline'>" + prompt3 + "</span>."
one simple way you can do it it as follows, note that you need to check for empty strings returned from prompt though, which is not handled in this answer,
var questions = ['an animal', 'a city', 'an activity'],
answers = [];
// create source string with placeholders that
// can be replaced with values in from prompts
var sourceText = "There was once was a {0} from {1} who liked to {2}."
//loop thru questions array and store answers in 'answers' variable
for (var q = 0; q < questions.length; q++) {
//create answer as span element
var question = questions[q],
answer = '<span style="text-decoration:underline;">';
answer += prompt('Enter ' + question);
answer +='</span>';
//update source text's 'qth' placeholder with answer
sourceText = sourceText.replace( new RegExp( "\\{" + q + "\\}", "g" ), function() {
return answer;
});
}
//update the target element's innerHTML
document.getElementById("story-space").innerHTML = sourceText;
You can try something like this by mapping all the prompts with an underline class.
var prompt1 = prompt("Enter a animal.");
var prompt2 = prompt("Enter a city.");
var prompt3 = prompt("Enter an activity.");
var prompts = [prompt1, prompt2, prompt3];
prompts = prompts.map(prompt => `<span class="underline">${prompt}</span>`)
var text = "There was once was a " + prompts[0] + " from " + prompts[1] + " who liked to " + prompts[1] + "."
document.getElementById("story-space").innerHTML = text;
.underline {
text-decoration: underline;
}
<div id = "story-space">
</div>
You can also try something like below where you just provide the pre-text for your prompt and let the Map and Reduce do the rest of the job for you.
let textPromptMap = new Map();
textPromptMap.set("There was once was a ", prompt("Enter a animal."))
textPromptMap.set(" from ", prompt("Enter a city."))
textPromptMap.set(" who liked to ", prompt("Enter an activity."))
const text = [...textPromptMap.keys()]
.reduce((a, b) =>
`${a}${b}<span class="underline">${textPromptMap.get(b)}</span>`, ""
)
document.getElementById("story-space").innerHTML = text;
.underline {
text-decoration: underline;
}
<div id = "story-space">
</div>
I'm looking some way to bold text in email and when I open the msgBox.
I want bold only headlines, like in picture below:
this is my script, you choose some cell in row that interests you and run the function. Function show information about data from every cell in row, like inforamtion about "Name" and "email". Then if you push send it will send email with this informations. I want bold headlines for better clarity.
function sendEmail(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var fr1 = ss.getSheetByName("Sheet1");
var cell = ss.getActiveCell().getRow();
var lastColumn = fr1.getLastColumn();
var lastRowValues = fr1.getRange(cell,1,1,lastColumn).getValues();
var Nr = lastRowValues[0][0];
var Data = lastRowValues[0][1];
var Information = lastRowValues[0][2];
var Name = lastRowValues[0][3];
var email = lastRowValues[0][4];
var urlOfSS = ss.getUrl();
var message = "Message" +
"\n " +
"\nNr: " + Nr +
"\nData: " + Data +
"\nInformation: " + Information +
"\nName " + Name +
"\nEmail: " + email +
"\n " +
"\n Link to spreadsheet:" +
"\n " + urlOfSS;
var emails = ss.getSheetByName("Sheet1");
var numRows = emails.getLastRow();
var emailTo = email;
var subject = "Zgłoszenie FAS - " + Nr;
if (email == ""){
Browser.msgBox('This row is empty - Choose another');
} else {
var ui = SpreadsheetApp.getUi();
var l = ss.getSheets()[0]
var response = ui.alert('Email', "Do you want email \nNr: " + l.getRange(cell, 1).getValue() + "\nData: " + l.getRange(cell, 2).getValue() + "\nInforamtion: " + l.getRange(cell, 3).getValue()
+ "\nName: " + l.getRange(cell, 4).getValue(), ui.ButtonSet.YES_NO);
if (response == ui.Button.YES) {
GmailApp.sendEmail(emailTo, subject, message);
} else {
Logger.log('The user clicked "No" or the dialog\'s close button.');
}
}
}
Regards
If I understand the requirement, Only the side headers(underlined in the screenshot) needs decoration.
While going through the Google Apps Scripts - Documentation, I came through this.
Hope this helps you.
Using the HtmlServices & HtmlOutputFromFile() would fulfill your requirement.
Please refer to Custom Dialogs. This would help you
https://developers.google.com/apps-script/guides/dialogs
My program needs to consist of a for loop, use both input functions already created ( name and number) and totals need to be acquired. I also need to be able to CANCEL and go to my doc.write where i would input name and number. I also need to give the user another chance to type in their name or number if they accidentally typed in number where letters should be and vise-versa. I think i have majority of the structure right, any help would be greatly appreciated!
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
/* INPUT NUMBER */
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn>min && numIn>max ){
numIn=prompt("Enter a valid number between 0-60");
return numIn;
}
</script>
<body>
<script type="text/javascript">
//DECLARATIONS
var wage=10.00;
var earned; // hrsWrked*wage
var totHrsWrked=0;
var totEarning=0;
var BR= "
";
var howMany;
var loopControl;
//INPUT & PROCESSING
howMany=parseFloat(prompt("How many employees are you inputing?"));
for(loopControl=1 ; loopControl <= howMany; ++loopControl){
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+=earned;
totHrsWrked+=inpNumber;
//OUTPUT
document.write("Name: "+ inpNam+ BR);
document.write("Hours Worked: " + inpNumber + BR);
document.write("Money Earned: $ " + earned + BR +BR);
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2) + BR);
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ BR+BR);
</script>
</body>
</html>
Here's the edited version of your code. :)
<! doctype html>
<html>
<body>
<script>
//DECLARATIONS
var wage=10.00, earned, totHrsWrked=0, totEarning=0, howMany;
//INPUT & PROCESSING
howMany=parseFloat(prompt("No of employees"));
for( var loopControl=1 ; loopControl <= howMany; ++loopControl)
{
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+= (+earned);
totHrsWrked+= (+inpNumber);
//OUTPUT
document.write("Name: "+ inpNam+ "<br>");
document.write("\n Hours Worked: " + inpNumber + "<br>");
document.write("Money Earned: $ " + earned + "<br><br>");
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2)+ "<br>");
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ "<br>");
//INPUT NAME
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
//INPUT NUMBER
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn<=min || numIn>=max ){
numIn=prompt("Enter a valid number between 0-60");
}
return numIn;
}
</script>
</body>
</html>
var pre = '<a href=someDirectoryPath';
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML = trailHTML + pre + getURL(trail[i]) + mid + trail[i] + post;
if(i!=(trail.length-1)) {
trailHTML += ' > ';
}
}
document.write(trailHTML);
trail is an arraylist of valid pages, like so:
['some name', 'another name','yet another name','name']
getURL just takes that name and adds a '-' in between words, which is the page name. This has been tested and works. (for example, getURL('some name') returns 'some-name')
The problem is, when run in IE9 (untested in other browsers), when I write trailHTML to the page, I only get the last element in the array. Why is this?
Let me know if you need any clarification...
function getURL(txt){
return txt.replace(/ /g,"-");
}
var trail = ['some name', 'another name','yet another name','name'];
///////////////////////////////////////////////////
var pre = '<a href="someDirectoryPath/'; // changed
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML += pre + getURL(trail[i]) + mid + trail[i] + post;
if(i<trail.length-1)trailHTML+=" > " // changed
}
document.write(trailHTML);
You have a syntax error in your for-loop: The open "{" on the if does not have a matching "}".
I ran a small sample in IE9 and got all items in the array, not just the last item as you report. Here's what I ran:
<script type="text/javascript">
function getURL(s){
return s.replace(" ", "-");
}
var trail = ['some name', 'another name','yet another name','name'];
var pre = '<a href=someDirectoryPath';
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML = trailHTML + pre + getURL(trail[i]) + mid + trail[i] + post;
if(i!=(trail.length-1)) {
trailHTML += " > ";
}
}
trailHTML = trailHTML + getURL(trail[0]);
document.write(trailHTML);
</script>
The output looked like this:
some name > another name > yet another name > namesome-name
Most likely your issue is caused by the syntax error, or in how the array is built/passed into your function.
function getList()
{
var string2 = "<img src='close.png' onclick='removeContent(3)'></img>" + "<h4>Survey Findings</h4>";
string2 = string2 + "<p>The 15 Largest lochs in Scotland by area area...</p>";
document.getElementById("box3text").innerHTML = string2;
var myList = document.getElementById("testList");
for(i=0;i<lochName.length;i++)
{
if(i<3)
{
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
else
{
var listElement = "Loch "+lochName[i];
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
}
}
This function generates a list with the 1st 3 elements being hyperlinks. When clicked they should call a function call getLoch(i) with i being the position of the item in the list. However when i pass it the value it just give it a value of 15, the full size of the array and not the position.
function getLoch(Val)
{
var str = "<img src='close.png' onclick='removeContent(4)'></img>" + "<h4>Loch " + lochName[Val] +"</h4>";
str = str + "<ul><li>Area:" + " " + area[Val] + " square miles</li>";
str = str + "<li>Max Depth:" + " " + maxDepth[Val] + " metres deep</li>";
str = str + "<li>County:" + " " + county[Val] + "</li></ul>";
document.getElementById("box4").innerHTML = str;
}
There are 2 errors in your code as far as I can see. The first is the way you create your link.
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
This will actually result in code like this:
<a href='javascript:getLoch(i)'>Loch name</a>
Passing a variable i is probably not what you intended, you want it to pass the value of i at the time your creating this link. This will do so:
var listElement = "<a href='javascript:getLoch(" + i + ")'>" + "Loch "+ lochName[i] + "</a>";
So why does your function get called with a value of 15, the length of your list? In your getList function, you accidently made the loop variable i a global. It's just missing a var in your loop head.
for(var i=0;i<lochName.length;i++)
After the loop finished, i has the value of the last iteration, which is your array's length minus 1. By making i a global, and having your javascript code in the links use i as parameter, getLoch got called with your array length all the time.