Probably a nube question but I have a line of code:
var c = message.substring(i, i + 1);
It works but in the new Google App Script editor, the string property "substring" has a double-underline under it, which seems to suggest that it's wrong, but it actually works!
"Show Fixes" gives me only two options - to ignore the "error" or disable checking, neither of which seems like what I want to do. Any ideas?
I think it is due to how the variable "message" is defined. I did a quick test trying to replicate your scenario and this is what I got:
With warning:
var message = 0
message = '123456789'
var c = message.substr(1, 5);
Without warning:
var message = '0'
message = '123456789'
var c = message.substr(1, 5);
Both cases have the same result without errors. If you provide more code I can check why the warning is appearing.
edit:
As you have said in the comments, your variable is being defined from the range of a SpreadSheet using getValue(), this method returns an object with the value of the cell. If you want to obtain a string you should use getDisplayValue(). You can also use the built-in method toString() to make sure that any variable is converted into a string.
References:
getValue()
getDisplayValue()
Related
I came across a problem with my code in Google Apps Script for Sheets. I want to get cell values from 3 different cells, concatenate them in a single string variable, and copy this string variable into a cell of my spredsheet, using the copyto function.
The problem is that Google Apps Script doesn't recognize copyto as a function, because it doesn't work with local string variables (it works fine with other function variables, such as getrange or else). Here is the part of my code that doesn't work :
var prog = f1.getRange("A3");
var jour = f1.getRange("B1");
var heure = f1.getRange("B2");
var texte = prog+" - "+jour+" à "+heure;
heure.copyTo(f2.getRange(1,2))
f1 is properly defined.
Where do I get this wrong ? Is there a workaround for this ?
Cheers
You say that f1 is properly defined and yet this example is complete and works as well.
function copy2test() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const sh2 = ss.getSheetByName('Sheet2');
sh.getRange('A1').copyTo(sh2.getRange('A2'));
}
Your example is incomplete because I cannot copy it and put it into my code editor and reproduce the same result as you get. So you haven't met the requirement for reproducibility. In my own mind I simply look at your example and assume that you don't know what you're talking about when you say it's defined properly.
You placed it in a snippet. So just run it: It returns an error with the following:
{
"message": "Uncaught ReferenceError: f1 is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 12,
"colno": 22
}
So you snippet result and I both agree. It's not defined properly.
For anyone coming across the same problem as I was, here is my solution. Because copyTo doesn't work with a string variable such as I had (or at least I don't know how to make it work), I used a different method which produces the same result.
Instead of heure.copyTo(f2.getRange(1,2))
I used f2.getRange(1,2).setValue([texte]);
which does what I wanted and work with a string variable.
I cant use send_Keys() method to input values in the current website im working on.
So im trying to use javascript to input values.
i tried click() and clear() together with send_keys() before i decided to use javascript but to my disappointment, it didnt work.
i use the javascript code to input value below
driver.execute_script("document.getElementById('CustCd').setAttribute('value', 'J590')")
and it worked.
But currently my code is inside a loop and the value changes, how can i replace J590 with a variable that gets the value?
Here is the code that i tried
ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
driver.execute_script("document.getElementById('CCRNo').value=ccr_No")
I know its wrong, any help would be appreciated. My Javascript is weak.
Just some side note if anybody would be able to solve my send_keys() error.
The function only takes in the first character that i send. For example, send_keys("J590") gives J, send_keys("J590-TE21") gives J-
First, the correct way to set the current value of an input is to assign to the value property. There is no attribute for the inputs current value (the value attribute is the input's default value, more here).
The rest is a special case of a general-purpose question: "How do I output a Python variable's value into JavaScript code?"
If the string you're outputting doesn't contain quotes or backslashes, you may get away with using a format string and outputting the value in quotes as Guy shows. (JavaScript has two kinds of quotes, ' and "; you only need to escape the kind you use around the value.) Those kinds of assumptions tend to break down, though; as soon as the string is Hi, I'm Joe that approach breaks.
In the general case, to ensure proper escaping and that all values are written correctly, you can use JSON:
import json
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').value = {json.dumps(value)};")
That outputs:
document.getElementById('CustCd').value = "J590";
Live Example
That way, you don't have to worry about quoting and escaping, it's all handled for you since valid JSON is valid JavaScript (thanks to a recent JavaScript specification fix; prior to that there was an edge case incompatibility that people almost never ran into).
It's also useful for numbers, or more complex things you might want to pass to hte JavaScript code. For instance:
import json
class Example:
foo = ""
bar = 0
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
value = Example("I'm a string with \"quotes\" in it.", 42)
print(f"const obj = {json.dumps(value.__dict__)};")
num = 42
print(f"const num = {json.dumps(num)};")
That outputs:
const obj = {"foo": "I'm a string with \"quotes\" in it.", "bar": 42};
const num = 42;
obj ends up being an object, because the initializer is a valid JavaScript object literal containing the data from the Example object. Similarly, num is a valid JavaScript number.
Live Example
You need to insert the variable as variable, not literal
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').setAttribute('value', '{value}')")
Using Javascript to input the values of a variable you can use the following solution:
ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
# ccr_No = J590
driver.execute_script("document.getElementById('CCRNo').value='" + ccr_No + "';")
An example, to input the values of a variable within Search Box of Google Home Page:
Code Block:
driver.get("https://www.google.com/")
value = 'J590'
driver.execute_script("document.getElementsByName('q')[0].value='" + value + "';")
Browser Snapshot:
You can find a relevant discussion in Selenium : How to send variable character strings through executeScript()
I know this question has been asked numerous times, but I really don´t get it.
I am creating a site in MVC, and I'm creating a JSON string from my model. I then want to pass it as argument to a JavaScript function that uses it to plot a graph.
Here is were I create the JSON string. This indeed creates a valid JSON string, I checked it at JSONLint.
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var weightsAsJsonString = serializer.Serialize(Enumerable.Select(Model, weight =>
new
{
date = weight.Date,
value = weight.Value
}));
}
Further down I create a JavaScript variable from it and pass it into the JavaScript function:
var jsonStringToGraph = #weightsAsJsonString;
google.setOnLoadCallback(drawVisualization(jsonstring));
When I run this, the console prints 'SyntaxError: Unexpected token &' at the line were I declare jsonStringToGraph. I googled around and concluded that I should put ' ' around #weightsAsJsonString, so I do that.
Anyway, in my drawVisualization, I do this:
function drawVisualization(teststring) {
.......
var parsedJson = JSON.parse(teststring);
This gives me SyntaxError: Unexpected token & Index:1
I know that the code at the bottom is what is causing the exception, but I do not understand why. Do anyone understand what I am doing wrong?
Edit: This is the weightsAsJsonString
[{"date":"\/Date(1434492000000)\/","value":100.2},{"date":"\/Date(1434578400000)\/","value":99.2},{"date":"\/Date(1434664800000)\/","value":101.2},{"date":"\/Date(1434751200000)\/","value":98.2},{"date":"\/Date(1434837600000)\/","value":97.2},{"date":"\/Date(1434924000000)\/","value":96.2},{"date":"\/Date(1435010400000)\/","value":95.2},{"date":"\/Date(1435096800000)\/","value":94.2}]
It sounds like your issue is trying to inject content via Razor into JavaScript. By default # will HTML-encode your content, which doesn't work in the context of JavaScript.
#Html.Raw(weightsAsJsonString) will work better, and then your JS will have a JavaScript object, so there's no need for the JSON.parse later on.
When you do var jsonStringToGraph = #weightsAsJsonString; you are actually defining a JSON object and not a JSON string.
Hence when you do JSON.parse(teststring); you are trying to parse an object instead of a string.
Either put apostrophes around the first declaration var jsonStringToGraph = '#weightsAsJsonString'; or simply do not try to parse it again.
I am using the new method: Utilities.formatString()
In the Google Documentation is says it is similar to sprintf %-style.
I searched and read this article about sprintf in PHP.
I cannot seem to get this to work as intended. It is meant to pad this 8 character string with 4 leading zeros. I know there are other ways to do this, But I am trying to get a handle on this sprintf / formatString thing.
var noFormat = "12345678";
var formatted = Utilities.formatString("%012s", noFormat);
I expected the var formatted to be equal to "000012345678".
my debugger tell me that formatted = 0, or sometimes it throws an error..
I am confused.
try it like this :
function xxx(){
var noFormat = '12345678'
var formatted = Utilities.formatString("%012d", noFormat);
Logger.log(formatted)
}
the different parameters that can be used are easy to find on the web, here is an example that explains how the argument must be evaluated in php but the usage is the same.
Logger result :
Over 1 hour on this. This is javascript code inside my index.php file.
function dostuff()
{
var thepath = document.location.search.substring(1);
alert('the path is ' + thepath + " (that's the full path)");
alert(thepath);
// TRIED THESE ALL -- NONE OF THEM WORK.
//var pathLen = String.length("thepath");
//var pathLen = String.length(thepath);
//var pathLen = thepath.length();
var pathLen = String.length(document.location.search.substring(1));
alert('pathLen is ' + pathLen);
}
The symptom: the first 2 alert boxes appear no problem and both show 'thepath' has a valid pathname in it, and it is the correct, expected path too.
But no matter what I try -- see the 4 different attempts, tried one at a time -- the final alert() box NEVER shows up.
Why is alert('pathLen is ' + pathLen) not showing up?
(The other thing is -- I'm using XDEBUG and xampp and Netbeans and the debugger will not let me put a breakpoint in this javascript code, so I can't even step into it to see what's happening, hence the use of the alert()'s in the code. I know the XDEBUG debugger I'm using in Netbeans works -- I've been using it all night to debug PHP code in a different.PHP file. When I set a breakpoint though in any Javascript code, a 'broken breakpoint' icon appears and I cannot find what that means in Netbeans documentation.)
I've never seen that syntax before. You might want to try:
var pathLen = thepath.length;
(You'd be best off debugging with Firebug)
var pathLen = thepath.length;
Length is a property of the string, not a function, so no need for the ().
The length is a property of your string rather than a method.
You should be able to access it via the following:
var pathLen = thepath.length;
When you say the alert box never shows up do you mean it never appears at all? If you're using FF you can open the error console from the Tools menu and clear it then refresh your page. It should highlight any JS errors you have in your code. That's the only reason I know of that the alert wouldn't show at all. (I don't think there is a class method for String.length() which is probably where the error is coming from.)
As for XDebug, as far as I know it's a PHP debugger only I don't think it can debug JS.
pathLen.length
No (). length is a property; if you add the (), it tries to use the value of the property as a function to call, resulting in an exception.