How do I add multiple values to a textarea in Javascript? - javascript

I'm new to Javascript and working on a problem, it's about making a website that allows a user to input a bid on an item along with a bid id. When they input both they press the submit button and the bid/bid id (along with the date and time) will display in a textarea.
It should allow for multiple bids to be submitted and to display but currently I can only get one to display. Any help as to how I can get multiple bids to display would be appreciated. Thank you
var bids = new Array();
var bidders = new Array();
var bidTime = new Array();
function writeBid() {
var historyText = " ";
for (var i = 0; i < bids.length; i++) {
historyText = bidTime[i] + " " + bids[i] + " " + bidders[i] + "\n";
document.bidForm.bidList.value = historyText;
document.bidForm.highBid.value = bids[i];
document.bidForm.bidId.value = " ";
document.bidForm.bidAmount.value = " ";
}
}
function addBid() {
bidders.unshift(document.bidForm.bidId.value);
bids.unshift(document.bidForm.bidAmount.value);
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var timeText = hours + ":" + minutes + ":" + seconds;
bidTime.unshift(timeText);
writeBid();
}
function removeBid() {
bids.shift();
bidders.shift();
bidTime.shift();
writeBid();
}

as #nnnnnn said using += with your text variable works perfect:
JavaScript
var bids = [10, 20, 30];
var bidders = ['tim', 'sam', 'john'];
var bidTime = ['10/2/2013','12/5/213','14/1/2023'];
function writeBid() {
var historyText = " ";
for (var i = 0; i < bids.length; i++) {
historyText += bidTime[i] + " " + bids[i] + " " + bidders[i] + "\n";
document.bidForm.highBid.value = bids[i];
document.bidForm.bidId.value = " ";
document.bidForm.bidAmount.value = " ";
}
document.bidForm.bidList.value = historyText;
}
HTML
<form name="bidForm" id="bidForm">
<input type="text" name="bidId" id="bidId"/>
<input type="text" name="bidAmount" id="bidAmount"/>
<input type="text" name="highBid" id="highBid"/>
<textarea name="bidList" id="bidList"></textarea>
</form>

Related

How to display today and 5 days with a counter and pass variables from build report down to the build alert function?

How to make "funding breakdown" show today and the next five business days without removing the “totalfunding” of just today and adding a counter to the “fundingbreakdown” so it comes out numbered?
I am passing through my variables from build report down to the build alert function, but for some reason, it is not passing the values from my variables. Why is that happening?
I appreciate your patience as this is my very first googleappscript.
function buildreport() {
const ss = SpreadsheetApp.getActive();
let data = ss.getSheetByName('February 2023').getRange("A:M").getValues();
var PrimorNonPrim = ss.getSheetByName('February 2023').getRange("A:A").getValues();
var Regionandentity = ss.getSheetByName('February 2023').getRange("B:B").getValues();
var Currency = ss.getSheetByName('February 2023').getRange("D:D").getValues();
var Amount = ss.getSheetByName('February 2023').getRange("F:F").getValues();
var RequestDate = ss.getSheetByName('February 2023').getRange("K:K").getValues();
var BankAcctCreditDate = ss.getSheetByName('February 2023').getRange("L:L").getValues();
var PayDate = ss.getSheetByName('February 2023').getRange("M:M").getValues();
let payload = buildAlert(data);
sendAlert(payload);
}
function buildAlert(data,PrimorNonPrim,Regionandentity,Currency,Amount,RequestDate,BankAcctCreditDate,PayDate) {
let today = new Date();
let filteredData = data.filter(row => {
let requestDate = new Date(row[10]);
return requestDate.getFullYear() === today.getFullYear() &&
requestDate.getMonth() === today.getMonth() &&
requestDate.getDate() === today.getDate();
});
let totalfunding = filteredData.reduce((total, row) => total + row[5], 0);
if (filteredData.length === 0) {
let fundingBreakdown = "Nothing coming up within 5 working days";
} else {
fundingBreakdown = (PrimorNonPrim + " " +"Entity" + " " + Regionandentity + " " + "Currency" + " " + Currency + " " + "Amount" + " " + Amount + " " + "Request Date" + " " + RequestDate + " " + "Bank Account Credit Date" + " " + BankAcctCreditDate + " " + "Pay Date" + " " + PayDate)}

Google Ads scripts - how to do customised or long rolling date ranges

I'm using the following script to export Google Ads data from my account, but I am stuck with Google's pre-set date ranges and can't figure out how/if it's possible to jimmy these. Ideal date range would be year to date, with the report refreshing each day and adding on a fresh day's data, but would also be interested if we can get all time to work.
I'm a coding novice, so apologies in advance.
Script:
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query);
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = currentSetting.ss + "<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
I've tried overwriting the data validation in the host spreadsheet, but think I need to amend the script itself also.

Filling QC Google forms with many pages using Google Sheet- Only Last line of code not working i.e. UrlFetchApp

I have learned how to automate google form filling using google sheet and app script. After many trial and error to apply the concept and automate it on simple google forms i have created, it worked absolutely fine.
But when I applied on the google form (which i seriously want to automate), everything works fine except the last line of code i.e. UrlFetchApp which brings google form link and data together and submit the form using "post" method but it's not working.
When i commented this line rest of the code executed without any error but this line is making my effort fail.
google form link for which i have created this code: https://docs.google.com/forms/d/e/1FAIpQLSc1uSOspwlen5Tcs0ccTxE4eia-scw3aVUwAsrVMdQBpk5ydA/viewform
function QC_form_fill() {
var wrkBk = SpreadsheetApp.getActiveSpreadsheet();
var wrkSht = wrkBk.getSheetByName("Qdata");
var formURL =""
var formData =""
var sdate = "";
var stime = "";
var mname = "";
var board = "";
var eclas = "";
var batch = "";
var slecture = "";
var sfaculty = "";
var ati1 = "";
var ta1 = "";
var ta2 = "";
var ta3 = "";
var sopen = "";
var stengage = "";
var teachpace = "";
var chtresp = "";
var tmmanmnt = "";
var vomod = "";
var sgrammar = "";
var qppt = "";
var fhndwrtng = "";
var drssup = "";
var lobjective = "";
var expstyl = "";
var sflow = "";
var cntnacc = "";
var demos = "";
var ati2 = "";
var poll = "";
var la = "";
var hw = "";
var prlfcd = "";
var sggstn = "";
var noOfRows = wrkSht.getRange("AI1").getDisplayValue();
for (i=2; i<=noOfRows; i++)
{
sdate =wrkSht.getRange("A"+i).getDisplayValue();
stime =wrkSht.getRange("B"+i).getDisplayValue();
mname =wrkSht.getRange("C"+i).getDisplayValue();
board =wrkSht.getRange("D"+i).getDisplayValue();
eclas =wrkSht.getRange("E"+i).getDisplayValue();
batch =wrkSht.getRange("F"+i).getDisplayValue();
slecture =wrkSht.getRange("G"+i).getDisplayValue();
sfaculty =wrkSht.getRange("H"+i).getDisplayValue();
ati1 =wrkSht.getRange("I"+i).getDisplayValue();
ta1 =wrkSht.getRange("J"+i).getDisplayValue();
ta2 =wrkSht.getRange("K"+i).getDisplayValue();
ta3 =wrkSht.getRange("L"+i).getDisplayValue();
sopen =wrkSht.getRange("M"+i).getDisplayValue();
stengage =wrkSht.getRange("N"+i).getDisplayValue();
teachpace =wrkSht.getRange("O"+i).getDisplayValue();
chtresp =wrkSht.getRange("P"+i).getDisplayValue();
tmmanmnt =wrkSht.getRange("Q"+i).getDisplayValue();
vomod =wrkSht.getRange("R"+i).getDisplayValue();
sgrammar =wrkSht.getRange("S"+i).getDisplayValue();
qppt =wrkSht.getRange("T"+i).getDisplayValue();
fhndwrtng =wrkSht.getRange("U"+i).getDisplayValue();
drssup =wrkSht.getRange("V"+i).getDisplayValue();
lobjective =wrkSht.getRange("W"+i).getDisplayValue();
expstyl =wrkSht.getRange("X"+i).getDisplayValue();
sflow =wrkSht.getRange("Y"+i).getDisplayValue();
cntnacc =wrkSht.getRange("Z"+i).getDisplayValue();
demos =wrkSht.getRange("AA"+i).getDisplayValue();
ati2 =wrkSht.getRange("AB"+i).getDisplayValue();
poll =wrkSht.getRange("AC"+i).getDisplayValue();
la =wrkSht.getRange("AD"+i).getDisplayValue();
hw =wrkSht.getRange("AE"+i).getDisplayValue();
prlfcd =wrkSht.getRange("AF"+i).getDisplayValue();
sggstn =wrkSht.getRange("AG"+i).getDisplayValue();
formURL ="https://docs.google.com/forms/d/e/1FAIpQLSc1uSOspwlen5Tcs0ccTxE4eia-scw3aVUwAsrVMdQBpk5ydA/formResponse?pageHistory=0,1"
formData= "&entry.1809185170=" + sdate + "&entry.772722605=" + stime + "&entry.1721230767=" + mname + "&entry.1024240207=" + board + "&entry.1132896225=" + eclas +"&entry.134507089="+ batch + "&entry.1349051916=" + slecture + "&entry.15763511=" +sfaculty + "&entry.1915124723=" + ati1 + "&entry.1154530333=" + ta1 + "&entry.1450881147=" + ta2 + "&entry.1627300385=" + ta3 + "&entry.928964249=" + sopen + "&entry.103830616=" + stengage + "&entry.1749915137=" + teachpace + "&entry.1879781398=" + chtresp + "&entry.1210552578=" + tmmanmnt + "&entry.1659325247=" + vomod + "&entry.377007890=" + sgrammar + "&entry.1207703694=" + qppt + "&entry.960993930=" + fhndwrtng + "&entry.343485399=" + drssup + "&entry.1988728268=" + lobjective + "&entry.1019203670=" + expstyl + "&entry.222077844=" + sflow + "&entry.465124407=" + cntnacc + "&entry.1299956408=" + demos + "&entry.956891355=" + ati2 + "&entry.60052266=" + poll + "&entry.125539625=" + la + "&entry.1193513376=" + hw + "&entry.705255491=" + prlfcd + "&entry.121026171=" +sggstn
var finalURL = formURL + formData
var options = {
"method" : "post"
};
UrlFetchApp.fetch(finalURL, options);
}
}

How to make a history of my var (Math.random)

I have a problem with my code, i wanna see my passed 4 generated number (Math.random), on a history box, but these numbers show out the same. Is there a way to delay a var?
I have tried putting var in order, but this makes no delay.
my html:
<div class="text-position-history">
<div class="text-style-history">
<p id="historyT"></p>
</div>
</div>
</body>
</html>
My javascript:
var green = 0;
var red = 0;
function odds(){
var result = Math.random();
if (result < 0.5)
{
document.body.style.backgroundColor = "green";
green++;
document.getElementById('greenT').innerHTML = "Times you survived: " + " " + green;
}
else{
document.body.style.backgroundColor = "red";
red++;
document.getElementById('redT').innerHTML = "Times you died: " + " " + red;
}
document.getElementById('resultT').innerHTML = "Guessed number: " + " " + result;
var history1 = result;
var history2 = history1;
var history3 = history2;
document.getElementById('historyT').innerHTML = "Guessed number: " + " " + result + " " + history1 + " " + history2 + " " + history3;
}
Is there a way to do this?
Why don't you just create an array and then append the new values of result to the array after you call Math.random()?
var resultHistory = new Array();
var result = Math.random();
resultHistory.push(result);
Then print out the array later on.
Why not just use array of numbers?
var _history = [];
function toHTMLElement(historyNode)
{
var node = document.createElement("div");
node.innerHTML = historyNode.text;
node.style.background = historyNode.win?'green':'red';
return node;
}
function renderHistory()
{
var result = document.getElementById("result");
result.innerHTML = "";
_history.forEach(function(e){
result.appendChild(toHTMLElement(e));
});
}
document.getElementById("form").addEventListener("submit", function(e){
e.preventDefault();
_history.push((Math.random()>0.5)?{win: true, text: 'You win'}:{win: false, text: 'You lose'});
if (_history.length > 3) _history.shift();
renderHistory();
});
<form id="form">
<input type="submit">
</form>
<div id="result"></div>
var green = 0;
var red = 0;
function odds(){
var result = Math.random();
if (result < 0.5)
{
document.body.style.backgroundColor = "green";
green++;
document.getElementById('greenT').innerHTML = "Times you survived: " + " " + green;
}
else{
document.body.style.backgroundColor = "red";
red++;
document.getElementById('redT').innerHTML = "Times you died: " + " " + red;
}
document.getElementById('resultT').innerHTML = "Guessed number: " + " " + result;
var myList = [result, result, result];
var history1 = myList.shift();
var history2 = myList.shift();
var history3 = myList.shift();
document.getElementById('historyT').innerHTML = "Guessed numbesr: " + " " + history1 + " " + history2 + " " + history3;
}
This still gives the same result?
I think actually changing the order of your history vars should fix it.
Change them to
var history3 = history2;
var history2 = history1;
var history1 = result;
Right now you are overwritung everything to results because:
var history1 = result
var history2 = history1 (history1 is already referring to result by now)

I cant solve this: to find the minimum number from an array that is input through prompt()

I cant solve this homework that needs to ask the user to enter student marks and output the minimum mark of the student, can someone please help me solve this problem:
<script>
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .').split(',');
return marks;
}
var studentMarks = getMarks();
var arrayLength = studentMarks.length;
var studentNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
studentNumber = (i + 1);
msg += 'student ' + studentNumber + ': ';
msg += studentMarks[i] + '%' + '<br />';
} document.getElementById('marks').innerHTML = msg; document.getElementById('marke').innerHTML = math.min.apply(null, studentMarks) + '%';
</script>
I will do that in the following way:
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .');
return marks.split(',').map(n => Number(n));
}
var marksArray = getMarks();
var studentMarks = Math.min(...marksArray);
var position = marksArray.indexOf(studentMarks);
var msg = 'Student ' + Number(position + 1) + ': ';
document.getElementById('marks').innerHTML = msg + studentMarks + '%';
<p id="marks"></p>

Categories