Issue appending newly changed variable and outputting with Javascript - javascript

I have an issue with the following code.
I am trying to change the content of a variable if a button is clicked and then output the corresponding content as part of a larger output. The output varies depending on if the inner button within the form is clicked.
Can anyone suggest a fix for this code or improvements?
In the output I should see a longer version as the extra block would be appended on to the newly created block and grab new id values generated. Any help would be great.
Here is my code:
<script>
$(document).ready(function() {
var currentID = 1;
$(':button#add').on('click',function() {
currentID++;
var clone = $('#content').clone();
clone.children('.content_title').attr('id', 'title_content-' + currentID);
clone.children('.content_more').attr('id', 'more_content-' + currentID);
clone.attr("id", "content_1");
clone.insertAfter('#content');
if(currentID >= 2) {
document.getElementById("add").style.display = "none";
}
});
});
</script>
</head>
<body>
<div>
<div>
<form action="" method="post">
<h1>Create Code</h1>
<fieldset>
<legend><span class="number"></span>Header</legend>
<label for="name">Title:</label>
<input type = "text" id = "title" />
</fieldset>
<fieldset id = "content">
<legend><span class="number"></span>Content</legend>
<label for="name">Title:</label>
<input class = "content_title" type = "text" id = "title_content" />
<label for="mail">Content:</label>
<input class = "content_more" type = "text" id = "more_content" />
</fieldset>
<input id = "add" type = "button" value = "Add" /> </form>
<button onClick="tryTest()">Code</button>
</div>
<div style = "float:left; width:48%; padding-left:10px;">
<p id="new_block"></p>
</div>
</div>
<script>
function tryTest() {
var quote = '"';
var start = "<pre><div class=" + quote + "newest" + quote + "></pre>";
var title = "title=" + quote + document.getElementById("title").value + quote;
var end = "<pre></div></pre>";
var start_1 = "{{widget type=" + quote + "new_version" + quote;
var title_1 = "title=" + quote + document.getElementById("title_content").value + quote;
var content_1 = "content=" + quote + document.getElementById("more_content").value + quote;
var end_1 = "template=" + quote + "other" + quote + "}}";
var title_2 = "title=" + quote + document.getElementById("title_content-2").value + quote;
var content_2 = "content=" + quote + document.getElementById("more_content-2").value + quote;
var widget = start_1 + "<br />" + title_1 + "<br />" + content_1 + "<br />" + end_1;
var widget_1 = start_1 + "<br />" + title_1 + "<br />" + content_1 + "<br />" + end_1 + start_1 + "<br />" + title_2 + "<br />" + content_2 + "<br />" + end_1;
if(add.clicked == false) {
document.getElementById("new_block").innerHTML = start + "<br />" + title + "<br />" + end + "<br /><br />" widget + "<br /><br />";
} else {
document.getElementById("new_block").innerHTML = start + "<br />" + title + "<br />" + end + "<br /><br />" widget_1 + "<br /><br />"";
}
</script>

This code is a strange mix of jQuery and vanilla JavaScript syntaxes...
But it would work if there was no parse error.
Those error were quite easy to find in a code editor like CodePen, by the way.
if(add.clicked == false) {
document.getElementById("new_block").innerHTML = start + "<br />" + title + "<br />" + end + "<br /><br />" + widget + "<br /><br />";
// Added a missing + sign ---> ---> ---> ---> here -------^
} else {
document.getElementById("new_block").innerHTML = start + "<br />" + title + "<br />" + end + "<br /><br />" + widget_1 + "<br /><br />";
// Added a missing + sign ---> ---> ---> ---> here -------^
}
} // Added this curly bracket to close the tryTest() function.
Just above this code block, is a condition to choose which string to append to new_block.
The if(add.clicked == false) { condition always evaluates to false, because add is not defined. So the property .clicked of undefined, obviously also is undefined...
Then "undefined" == false is false... And makes the else block to always execute.
This condition fixed will avoid the Cannot read property 'value' of null error on "Code" click if the "Add" has not been clicked.
There is a couple ways to determine if the "Add" button has been clicked.
Check if the element title_content-2 exist
Use a boolean "flag" turned to true on "add" click
Adding a class to the "Add" button on click
I will let you think about the solution you would prefer and try it.
Here is your code freed of the mentionned syntax errors in CodePen.

Related

Unable to properly add value to a cell using GAS

I adopted the script below and I am having two issues.
The "Email Sent" value does not update in the correct row. Let's say I sent an email to the recipient in row 5, instead of appearing in column 10 of row 5 "Email Sent" appears in column 10 of row 21.
Sometimes "Email Sent" does not appear at all even though I know the email went out.
I've tried everything I can think of but I can't make it work.
//Send approval or non-approval of time off request
function sendLeaveRequestDecisions() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses 2");
var dataRange = sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn());
var data = dataRange.getValues();
for (i in data) {
var startRow = 2; //First row of data to process
var rowData = data [i];
var startdate = rowData [2];
var enddate = rowData [3];
var type = rowData [4];
var email = rowData [5];
var recipient = rowData [1];
var decision = rowData [7];
var comments = rowData [8];
var emailstatus = rowData [9]
var emailPattern = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|aero|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|name|museum|name|net|org|pro|tel|travel)\b/;
var validEmailAddress = emailPattern.test(email);
if (validEmailAddress == true && emailstatus != "Email Sent") {
var message = "<HTML><BODY>"
+ "<P>Dear " + recipient + ","
+ "<br /><br />"
+ "<P>The following request:"
+ "<br /><br />"
+ "<b>Type: </b>" + type + "<br />"
+ "<b>From: </b>" + startdate + "<br />"
+ "<b>To: </b>" + enddate + "<br />"
+ "<br /><br />"
+ "<b>is </b>" + decision + "<br />"
+ "<b>Comments </b>" + comments + "<br />"
+ "<br /><br />"
+ "Diane"
+ "<br /><br />"
+ "</HTML></BODY>";
MailApp.sendEmail(email, "Regarding your leave request", "", {htmlBody: message});
sheet.getRange(i + 2,10).setValue("Email Sent");
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
Try this:
Mostly what was wrong was that you didn't escape the forward slashes contained in your regex expression. I'm surprised it ran at all. It runs okay for me. You might like to take a look at Utilities.formatString() for building your message. Just click on Help/API Reference. From there it's down at the bottom left where it says Script Service/Utilities.
Personally, I wouldn't put flush in a loop like that. I moved startRow and emailPattern out of the loop as well. They don't change. The less you put in a loop the faster it runs. I commented out the MailApp.sendmail because I didn't actually want to send email and I assume that you got that right.
function sendLeaveRequestDecisions() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Index Generation");
var dataRange = sheet.getRange(2,1,sheet.getLastRow()-1,sheet.getLastColumn());
var data = dataRange.getValues();
var startRow = 2; //First row of data to process
var emailPattern = /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|aero|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|name|museum|name|net|org|pro|tel|travel)\b/;
for (var i=0;i<data.length;i++){
var rowData = data [i];
var startdate = rowData[2];
var enddate = rowData[3];
var type = rowData[4];
var email = rowData[5];
var recipient = rowData[1];
var decision = rowData[7];
var comments = rowData[8];
var emailstatus = rowData[9];
var validEmailAddress = emailPattern.test(email);
if (validEmailAddress == true && emailstatus != "Email Sent") {
var message = "<HTML><BODY>" + "<P>Dear " + recipient + "," + "<br /><br />" + "<P>The following request:" + "<br /><br />" + "<b>Type: </b>" + type + "<br />" + "<b>From: </b>" + startdate + "<br />" + "<b>To: </b>" + enddate + "<br />" + "<br /><br />" + "<b>is </b>" + decision + "<br />" + "<b>Comments </b>" + comments + "<br />"+ "<br /><br />" + "Diane"+ "<br /><br />" + "</HTML></BODY>";
//MailApp.sendEmail(email, "Regarding your leave request", "", {htmlBody: message});
sheet.getRange(i + 2,10).setValue("Email Sent");
}
}
//SpreadsheetApp.flush();
}
I did something similar but quite differently and I've personally found this kind of response unhelpful in the past so do tell me to leave it alone if you feel like that.
If you would like me to try writing something though, which you and others could run, I will do that. My example of doing this is as personal - even more so - than yours.

Print the text from all inputs

I need to print all the text from inputs in the div "readyorder". So for it prints some of them but I need to print also the text from inputs which are showing up after I click on "AddAuthor". So when I click on "AddAuthor" the next three inputs are showing up and I need to print them in the same div as additional informations. It must happen to all inputs which are showing up. Can I ask for help??
<!DOCTYPE html>
<html>
<body>
<input type="text" name="file-1" />
<input type="text" name="surname-1" />
<input type="submit" value="Add author" id="add_input" />
<form name="add_file" enctype="multipart/form-data" method="post">
</form>
<hr>
<div id="readyorder"></div>
<br />
<script type="text/javascript">
window.onload = Load;
var number = 0;
function Load() {
document.getElementById('add_input').onclick = AddElement;
}
function AddElement() {
var element1 = document.createElement('input');
var element2 = document.createElement('input');
var element3 = document.createElement('input');
var label1 = document.createElement('label');
var label2 = document.createElement('label');
var label3 = document.createElement('label');
var button = document.createElement('input');
label1.innerHTML = "<br />Author's Name " + number + "<br />";
element1.setAttribute('type', 'text');
element1.setAttribute('id', 'name' + number);
element1.setAttribute('placeholder', 'Name...');
label1.appendChild(element1);
label2.innerHTML = '<br /> Initial ' + number + '<br />';
element2.setAttribute('type', 'text');
element2.setAttribute('id', 'initial' + number);
element2.setAttribute('placeholder', 'Initial...');
label2.appendChild(element2);
label3.innerHTML = '<br />Surname ' + number + '<br />';
element3.setAttribute('type', 'text');
element3.setAttribute('id', 'surname' + number);
element3.setAttribute('placeholder', 'surname...');
label3.appendChild(element3);
button.setAttribute('onclick', 'getText(' + number + ')');
button.setAttribute('type', 'button');
button.setAttribute('value', 'Button ' + number);
document.forms['add_file'].appendChild(label1);
document.forms['add_file'].appendChild(label2);
document.forms['add_file'].appendChild(label3);
document.forms['add_file'].appendChild(button);
number++;
}
function getText(id) {
var name = document.getElementById("name" + id);
var initial = document.getElementById("initial" + id);
var surname = document.getElementById("surname" + id);
var div = document.getElementById("readyorder")
var wydawnictwo = document.getElementById("title");
var rokwydania = document.getElementById("otherinfo");
var div = document.getElementById("readyorder")
div.innerHTML = "(" + "," + " " + "s." + " " + page.value + ")" + "(" + name.value + " " + initial.value + "," + " " + "s." + " " + surname.value + ")" + year.value;
}
</script>
</body>
</html>
Array.from(document.querySelectorAll('input[type=text]')).forEach(input =>
console.log(`INPUT of name ${input.name} has value = ${input.value}.`)
)
By that, you will print all text inputs existing in the page.
Array.from(document.querySelectorAll('input[type=text]')).forEach(input =>
console.log(`INPUT of name ${input.name} has value = ${input.value}.`)
)
<input type="text" name="firstname" value="Agg" />
<input type="text" name="lastname" value="Garg" />

how to have a css in javascript when onsubmit trigger in another window?

function welcome() {
var Name = document.getElementById("name").value;
var form = "<h1>" + "HI " + Name + " READY YOUR REFLEXES!" + "</h1>";
document.write(form);
return false;
}
how to have a css in javascript when onsubmit trigger in another window?
Being quick :
A way for adding a style to your inserted title is to add a class to it :
var form = "<h1 class='myclass'>HI " + Name + " READY YOUR REFLEXES!" + "</h1>";
Then create a css rule:
.myclass{color:red;}
function welcome(){
var Name = document.getElementById("name").value;
//var form = "<h1>" + "HI " + Name + " READY YOUR REFLEXES!" + "</h1>";
var form = "<h1 class='myclass'>HI " + Name + " READY YOUR REFLEXES!" + "</h1>";
document.getElementById("result").innerHTML=form;
return false;
}
.myclass{color:red;}
<button type="button" onclick="welcome()" value="Welcome">Welcome</button>
<input id="name" type="text" value="">
<div id="result"></div>

javascript function doesnt work

I'll rephrase my question
I wrote this code and I don't understand why it doesn't work...
I want to create something that one a person come's to the website to order sandwich he write's one of the options I wrote in the website and then it display's the sandwich he chose and the the ingredients in the sandwich (the ingredients are all the arrays)
I'll add my html code as well, and if someone can write an example for the right code it will be much more helpful to me.
Thanks a lot in advance!
JavaScript code:
var avucado = ["eggs ","avucado ","tommato ","mayonnaise ","pickles ","gamba"];
var eggSalad = ["eggs ","dill ","mayonnaise ","pickles"];
var tuna = ["tuna ","coriander ","pickles ","mayonnaise ","gamba"];
var cheeze = ["yellow cheeze ","mayonnaise ","tommato ","cucumber"];
var sausage =["sausage ","mustard ","mayonnaise ","tommato ","pickles"];
var choice1 = ("you chose:");
var choice2 = ("the ingredients of your sandwich are:")
var food = function(foodName)
{
if (document.getElementById("input").value = avucado) {
document.write(choice1 + " " + 'avucado.'+ "<br /><br />" + " " + choice2 +
" " + avucado + ".");
}else if(document.getElementById("input").value = eggSalad) {
document.write(choice1 + " " + 'egg salad.'+ "<br /><br />" + " " + choice2 +
" " + eggSalad + ".");
}else if(document.getElementById("input").value = tuna) {
document.write(choice1 + " " + 'tuna.'+ "<br /><br />" + " " + choice2 +
" " + tuna + ".");
}else if(document.getElementById("input").value = cheeze) {
document.write(choice1 + " " + 'yellow cheeze.'+ "<br /><br />" + " " + choice2 +
" " + cheeze + ".");
}else if(document.getElementById("input").value = sausage) {
document.write(choice1 + " " + 'tuna.'+ "<br /><br />" + " " + choice2 +
" " + tuna + ".");
}
else(document.getElementById("input".value != avucado,eggSalad,tuna,cheeze,sausage){
document.write("Error, please chose one of the sandwich's on the list");
}
};
HTML code:
<html>
<head>
<title>Hello World!</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="script.js"> </script>
</head>
<body dir="rtl">
<h1> wich sandwich would you like to order? </h1>
<form>
<input type="text" id="input" /><br />
<button type="button" id="button" value="submit" onclick="food()">submit</button><br />
</form>
</body>
</html>
Replace all occurrences of:
document.getElementById("input").value =
With:
document.getElementById("input").value ==
The single "equals" sign (=) is an "Assignment" operator.
The double "equals" sign (==) is an "Comparison" operator.
In your if's, you were assigning the foodstuffs' contents to the input's .value, instead of checking for equality.
To check if the value is in the arrays, you should do something like this:
if(avucado.indexOf(document.getElementById("input").value) !== -1){
So, if the value is in the array avucado, then do what's below the if.
Last, this else statement of yours needs some fixing:
else(document.getElementById("input".value != avucado,eggSalad,tuna,cheeze,sausage){
document.write("Error, please chose one of the sandwich's on the list");
}
Replace that with:
else if(avucado.concat(eggSalad,tuna,cheeze,sausage).indexOf(document.getElementById("input").value) == -1){
document.write("Error, please chose one of the sandwich's on the list");
}
Now, instead of document.write("text"), I'd suggest using DOM manipulation:
In your HTML, add an element like this:
<span id="message"></span>
Then, in your JS:
document.getElementById("message").innerHTML = "text";

Maintaining Line Breaks Through Facebook API Usage

When using the api and javascript to display the description of an event, how can i preserve the line breaks?
query.wait(function(rows) {
document.getElementById('debug').innerHTML =
new Date(rows[0].start_time * 1000) + "<br />" +
rows[0].start_time + "<br />" +
rows[0].end_time + "<br />" +
rows[0].location + ", " +
rows[0].venue['street'] +
rows[0].venue['city'] + ", " +
rows[0].venue['state'] + "<br />" +
rows[0].description;
;
});
You can use a <pre> element to preserve white space characters, such as \t and \n.

Categories

Resources