Javascript Includes giving unexpected results - javascript

This is becoming a little strange because I think it's something very simple and for some reason still giving unexpected results.
So basically I have an input field and I have a table.
The user can type in the input field and search within a specific column of the table.
So a typical cell might have a date, for example "24/03/2020".
Now if the user types in "24" using includes I get false.
This is a sample code:
let _t = $('input[data-search="date"]').val(); //gets the user input text
let _c = $(v).find('td[data-query="date"]').html(); //gets the cell data
var _r = (_t.toLowerCase().includes(_c.toLowerCase()))
Now when I output the result in the console console.log(_t, _c, _r), I get the following result if the user inputs '24' and there is a cell containing '24/03/2020'
24 – "24/03/2020" – false
This is very strange! Somebody please help!

includes searches for a substring inside a of a string. So you have to search 24 inside 24/03/2020, not 24/03/2020 inside 24.
So just use this line of code:
var _r = (_c.toLowerCase().includes(_t.toLowerCase()))
instead of:
var _r = (_t.toLowerCase().includes(_c.toLowerCase()))

Related

Input Tag returning Empty String after inputting 1st character

I am trying to get the values from an input box. When I first input a character and hit enter it returns an empty string in console and I only get the first value after inputting the 2nd value. For example: If I write 'a' in the input box and hit enter it returns an empty string and then if I write 'b' in the input box then it returns a and so on. Here's my code -
let opts = [];
let optInputs = document.getElementsByName("option_values[]");
for(let j = 0; j < optInputs.length; j++){
opts.push(optInputs[j].value);
}
If I only console.log optInputs then I am getting the Nodelist and inside it, I am getting the values immediately but whenever I want to access it in a loop I seem to get an empty string after I enter the first character. I have faced an issue like this. Can anyone please help me out here I have been scratching my head over this issue for 3 days now.
Try using a different selector like querySelector /getElementById / getElementByClassName
1.I need someway to call my code. here I am telling my form to execute the function every time the user submit the form.
i am also using preventdefault(); inside my function because I don't want it to reload my page.
2.getting the value of the input withdocument.querySelector(".option_values").value; & storing it in optInputs.
3.pushing the value of optInputs into the array opts.
4.document.querySelector(".option_values").value = ""; to clear the input.
everytime you hit enter it will go back to empty.otherwise user has to backspace and removing previous characters.
let opts = [];
function myFunction(event) {
event.preventDefault();
let optInputs = document.querySelector(".option_values").value;
opts.push(optInputs)
document.querySelector(".option_values").value = "";
console.log(opts)
}
<form onsubmit="myFunction(event)">
<input class="option_values" type="text" />
</form>

Concate String to a formula in app script

I have a values in google sheet and the format is =+40,-58. This give me ERROR! because the sheet is taking it as formula.
I can manually edit this by adding ' single qoute before equal sign but when i append qoute using script it append qoute with ERROR!.
Tried multiple thing like getting cell type, convert it to string.
Tried set formula method but it appends another equal sign before the cell value
please check the code below
if (//my condition){
sheet.getRange(i,col_in+1).setValue("'"+colvalue)
I am looking for possible solutions like, how can I get the actual value of the cell from fx
or
How can i append a single quote with the cell value instead of appending quote with ERROR.
please see the screenshot of the sheet
Descrition
Because the formula is giving "#ERROR" you need to getFormula and use setValue
Script
function test() {
let cell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A6");
let value = cell.getFormula();
if( value !== "" ) {
console.log("formula = "+value);
cell.setValue("'"+value);
}
}
Console.log
7:30:31 AM Notice Execution started
7:30:31 AM Info formula = =+52,-64
7:30:32 AM Notice Execution completed

Form's App Script does not replace fields in template accurately

I have a simple script to generate a doc and PDF upon form submission. It worked well on simple template (e.g. Only 1 sentence, First name, Last name and Company name).
However, when I use a template that's longer, having many fields, and formatting, the code runs but replace the text randomly.
I have tried to hardcode the fields of forms in ascending order as the doc template. However it still replace the text randomly
Can anybody points out what have I done wrong?
My code:
function myFunction(e) {
var response = e.response;
var timestamp = response.getTimestamp();
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
var file = DriveApp.getFileById('XXXXX');
var folder = DriveApp.getFolderById('XXXXX')
var copy = file.makeCopy(companyName + '_one pager', folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText('{{Company Name}}', companyName);
body.replaceText('{{Name}}', name1);
body.replaceText('{{Position}}', position1);
body.replaceText('{{Email}}', emailAdd1);
body.replaceText('{{Linkedin}}', linkedin1);
body.replaceText('{{Fun Fact}}', funFact1);
body.replaceText('{{Game Stage}}', gameStage);
body.replaceText('{{Game Story}}', gameStory);
doc.saveAndClose();
folder.createFile(doc.getAs("application/pdf"));}
My template -
Result -
Question - Does that mean the array declaration in line 3 was supposed to match the order of my form responses columns?
You can use Regular Expresion:
body.replace(/{{Company Name}}/g, companyName); // /g replace globaly all value like {{Company Name}}
Finally I found what have went wrong after so many trials and errors!
The reason is because I declared the array variables randomly without following the order of the form responses columns.
The issue is with the part -
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
It's actually pulling responses from the spreadsheet, and should be corrected in order. The wrongly mapped values was what causing the replacement of text went haywire. I corrected the order as per form responses and it is all good now.
Learning points:
If you swapped around the variables, what response.getItemResponses().map(function(f) {return f.getResponse()} does is that it will go through the form responses column by column in order, and it will map the content to the wrong variable. As a result, when you replace your text later using body.replaceText('{{Game Stage}}', gameStage), there might be possibility that whatever stored in gameStage might be name1. Hence the replaced text will be wrong. And you will scratch your head until it bleeds without knowing why.
I saw #Tanaike's comment after I found the answer, but totally spot on!

Automatically replace dots with commas in a Google Sheets Column with Google Script

I have a WooCommerce store, which is connected with Zapier to a Google spreadsheet. In this file, I keep track of the sales etc. Some of these columns contain -obviously- prices, such as price ex VAT, etc. However, for some reason the pricing values are stored in my spreadsheet as strings, such as 18.21.
To be able to automatically calculate with these values, I need to convert values in these specific columns to numbers with a comma as divider. I'm new to Google Script, but with reading some other post etc, I managed to "write" the following script, which almost does the job:
function stringIntoNumber() {
var sheetActive = SpreadsheetApp.openById("SOME_ID");
var sheet = sheetActive.getSheetByName("SOME_SHEETNAME");
var range = sheet.getRange("R2:R");
range.setValues(range.getValues().map(function(row) {
return [row[0].replace(".", ",")];
}));
}
The script works fine as long as only values with a dot can be found in column R. When values that belong to the range are changed to values with a comma, the script gives the error:
TypeError, can't find the function Replace.
Select the column you want to change.
Goto Edit>Find and Replace
In Find area put "."
in Replace with area put ","
The error occurs because .replace is a string method and can't be applied to numbers. A simple workaround would be to ensure the argument is always a string, there is a .toString() method for that.
in your code try
return [row[0].toString().replace(".", ",")];
The locale of your spreadsheet is set to a country that uses commas to seperate decimal places. Zapier however seems to use dots and therefore google sheets interprets the data it gets from Zapier as strings since it can't interpret it as valid numbers.
If you change the locale to United States (under File/Spreadsheet settings) it should work correctly. But you may not want to do that because it can cause other issues.
You got a TypeError because the type was number and not string. You can use an if statement to check the type before calling replace. Also you should convert the type to 'number' to make sure it will work correctly independent of your locale setting.
range.setValues(range.getValues().map(function(row) {
if(typeof row[0] === "string") return [Number(row[0].replace(",", "."))];
else return row;
}));
In this case I convert , to . instead of the other way around since the conversion to number requires a ..
Click on Tools > Script Editor.
Put this on your macros.gs (create one if you don't have any):
/** #OnlyCurrentDoc */
function ReplaceCommaToDot() {
var range = SpreadsheetApp.getActiveRange();
var col = range.getColumn();
var row = range.getRow();
function format(str) {
if(str.length == 0) return str;
return str.match(/[0-9.,]+/)[0]
.replace('.','')
.replace(',','.');
}
var log = [range.getRow(), range.getColumn()];
Logger.log(log);
var values = range.getValues()
for(var row = 0; row < range.getNumRows(); row++){
for(var col = 0; col < range.getNumColumns(); col++){
values[row][col] = format(values[row][col]);
}
}
range.setValues(values);
}
Save. Go back to the spreadsheet, import this macro.
Once the macro is imported, just select the desired range, click on Tools > Macro and select ReplaceCommaToDot
Note: This script removes the original ., and replaces , by .. Ideal if you are converting from US$ 9.999,99 to 9999.99. Comma , and whatever other text, like the currency symbol US$, were removed since Google Spreadsheet handles it with text formatting. Alternatively one could swap . and ,, like from US$ 9.999,99 to 9,999.99 by using the following code snippet instead:
return str.match(/[0-9.,]+/)[0]
.replace('.','_')
.replace(',','.')
.replace('_',',');
An alternative way to replace . with , is to use regex functions and conversion functions in the Sheets cells. Suppose your number is in A1 cell, you can write this function in any new cell:
= IF(REGEXMATCH(TO_TEXT(A1), "."), VALUE(REGEXREPLACE(TO_TEXT(A1), ".", ",")), VALUE(A1))
These functions do the following step:
Convert the number in the target cell to text. This should be done because REGEXMATCH expects a text as its argument.
Check if there is a . in the target cell.
If there is a ., replace it with ,, and then convert the result to a number.
If there is no ., keep the text in the target cell as is, but convert it to a number.
(Note : the Google Sheets locale setting I used in applying these functions is United States)
I have different solution.
In my case, I`m getting values from Google Forms and there it is allowed use only numbers with dot as I know. In this case when I capture data from Form and trigger script which is triggered when the form is submited. Than data is placed in specific sheet in a specific cell, but formula in sheet is not calculating, because with my locale settings calculating is possible only with a comma not dot, that is coming from Google Form.
Then I use Number() to convert it to a number even if it is already set as a number in Google Forms. In this case, Google Sheets script is converting number one more time to number, but changes dot to comma because it is checking my locale.
var size = Number(sizeValueFromForm);
I have not tested this with different locale, so I can`t guarantee that will work for locale where situation is opposite to mine.
I hope this helps someone. I was looking for solution here, but remembered that some time ago I had similar problem, and tried this time too and it works.
=IF(REGEXMATCH(TO_TEXT(F24);"[.]");REGEXREPLACE(F24;"[.]";",");VALUE(F24))
Works for me
If find dot replace with comma if not, put value

Is there a way to read hidden inputs with array-like names correctly in all browsers?

An interface has a number of hidden inputs called "kilos[]" or "precio[]". These are then passed on to a PHP function that handles them like an array. All that is fine. However, if I require to delete a row (tr) from the table (where the inputs will be deleted, too) then I do the following:
var e=t.parentNode.parentNode;
var ix=e.sectionRowIndex;
var p=e.parentNode;
var f2=t.form;
var kl= p.rows.length > 2 ? f2.elements["kilos[]"][ix].value : f2.elements["kilos[]"].value;
var pc= p.rows.length > 2 ? f2.elements["precio[]"][ix].value:f2.elements["precio[]"].value;
f2.tokilos.value-=parseFloat(kl).toFixed(2);
f2.tomonet.value-=parseFloat(pc).toFixed(2);
f2.totamb.value-=parseFloat(kl).toFixed(2);
p.removeChild(e);
Notice that this code only works in Chrome, nowhere else. Can you see what needs to be done in order to get the correct values of "kilos[]" and "precio[]"?
If the total number of rows left in the table is greater than 2, then I can use:
f2.elements["kilos[]"][ix].value
However, if the number of rows is not greater than 2, I need to do this, instead:
f2.elements["kilos[]"].value
That is the only way for it work and only in Chrome. sectionRowIndex returns the correct values all the time; it is the form.elements["name[]"][ix].value that by itself does not behave as expected when the number of rows in the tbody is only 1 (the last one). The code works and does what I need it to be done; however, it is odd that such a workaround is needed.
Is there a way to make this work in all browsers, using pure javascript?
You could use document.getElementsByName('kilos[]') which will always return an array-like object.
If you want to restrict the search to a specific element, you can use querySelectorAll:
var inputs = f2.querySelectorAll('[name="kilos[]"]');
// or
var inputs = document.querySelectorAll('#formID [name="kilos[]"]');

Categories