pass String to function writing javascript - javascript

I'm trying to pass a string argument to JavaScript function.
for some reason, it can get only ints.
I put here only the syntax of the string, since I know that this is the problem because it worls with int.
Code inside sending function:
String counter = "hey";
out.println("<script>parent.update(\'' + counter + '\')</script>");
out.flush();
Eventually I'd expect following update function on my HTML page to be called with value of counter as shown above:
<script>
function update(p) { alert(p); }
</script>
as I mentioned, the javascript file does alert when I send an int, but doesn't react when I send a string.

What you are trying to do called "string interpolation" and used in other languages - you can have formatting string and get values automatically inserted to it.
The code you've used does not do that - since you pass just single string to out.println it is printed as is.
Your options
construct string with concatenation
out.println("<script>parent.update('" +
counter +
"')</script>");
use String.format as shown in String variable interpolation Java
out.println(String.Format("<script>parent.update('%s')</script>",
counter));
Note: if value you are trying to pass to JavaScript function may contain quotes (especially if coming from user's input) you'd need to escape it first.

Related

InvokeScript works but WebPage replies "invalid argumment"

my script function is already defined in current loaded document
I am using
WebBrowser.InvokeScript Method (String, Object[])
as specified in MSDN to invoke a javascript method with the same arguments specified here in href.
<a style="cursor: auto ! important;" id="13185-SL-CK-0" href="javascript:jpBook($('#13185-SL-CK-0'),'13185','SDAH','DBG','24-10-2015','SL','CK',3,false);" tabindex="1">Book Now</a>
My Code is :
webBrowser1.Document.InvokeScript("jpBook", new object[] { "$('#13185-SL-CK-0')", "'13185'","'SDAH'","'DBG'","'24-10-2015'","'SL'","'CK'","3","false" });
However this doesn't work and i get a message from WebPage in a MessageBox that the arguments supplied to it are invalid.
However as you can see i have supplied the correct arguments.I am using a WebBrowserControl and have modified registry values for app to ensure that it emulates IE11
My assumption is that you need to pass without the inner single quotes as the JavaScript function is expecting a string SDAH for example not the string 'SDAH'
I haven't used the exact same api but in my project I'm invoking the script on a WebView passing a string from a variable which is just a normal string without the single quotes, also looking the MSDN example it looks they are doing the same.
For example I'm using:
anchorId is just a simple string variable like "Test1234"
C# code:
sender.InvokeScript("gotoAnchor", new string[] { anchorId });
Javascript code
function gotoAnchor(anchor) {
var myanchor = anchor;
var target_top=jQuery('#' + myanchor).offset().top-45;
$('html, body').animate({ scrollTop: target_top }, 600);
}
If I were you I'd try first with a simple function with just one parameter to see if it works, eg pass a string and write some text on html element, and then try the number and boolean values, at the end I'd also pass the first one
$('#13185-SL-CK-0' only like this "13185-SL-CK-0"
and will modify the js function to find the element inside as it might be expecting jquery object right now as parameter
Hope my assumptions are correct and this works out for you

value is taken as parameter on function

im passing a value retrieved from an ajax call to a function like this way:
nuevaFila+='<td><input type="button" value="Agregar" onclick="AgregarSuvenir('+item.CODSUVENIR+');"></td></tr>';
and we i clicked the button it throws an undefinided "variable" but is not a variable, i just wanted to pass it as a string, and the value passed to the function is taken as a variable, i tried
onclick="AgregarSuvenir("'+item.CODSUVENIR+'") and onclick="AgregarSuvenir('+item.CODSUVENIR+""')
but this fails
someone help me how to pass the value as string and not be taken a a variable.
thanks is advance
This is a simple case of matching quotes. Because you use single quotes to delimit the string, you must add escaped quotes inside your function call in order for the inserted value to be treated like a string.
Here are two possible solutions that escape the quotations to allow for the parameter to the AgregarSuvenir function to be treated like a string:
nuevaFila+='<td><input type="button" value="Agregar" onclick="AgregarSuvenir(\''+item.CODSUVENIR+'\');"></td></tr>';
or:
nuevaFila+="<td><input type=\"button\" value=\"Agregar\" onclick=\"AgregarSuvenir('"+item.CODSUVENIR+"');\"></td></tr>";
found it!
it has to be formatted like stated on this post: pass string parameter in an onclick function
onclick="AgregarSuvenir(\''+item.CODSUVENIR+'\')

cannot pass string to function

I'm using javascript and I try to pass a string to a function , like so
//example string
var f="a";
//add button that sends the value of f to the function
document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere("+f+");'> ";
function gothere(a){
alert(a);
}
I never see the alert and in console I see a is not defined (refers to the f I guess?)
If i set the f var to be a number then I see the alert.
What am I missing?
Thanks in advance
EDIT
I was thinking maybe something like
var buttonnode= document.createElement('input');
document.getElementById("mydiv").appendChild(buttonnode);
buttonnode.onclick=gothere(f);
Wont work for the same reason?
When your HTML get's rendered, you get onclick='gothere(a);', but the actual a variable doesn't exist in this context, you want to pass the value of f, as a string, so you'll need to use onclick='gothere(\""+f+"\");'. Note the extra quotes inside the parens. This will render to onclick='gothere("a");' thus passing the string.
When using a number, it works, because calling onclick='gothere(5);' is valid, since a variable can't be named 5, and it passes the number.
Actually, you don't have an a in your code. You are using variable f to denote a. So using this would help you:
var f="a";
// write the remains of the code as they are..
function gothere(f) {
alert(f);
}
Now when you'll call the function, there will be an alert of a in the browser.
Also, try wrapping the content in "" double qoutes to let the code understand that this is a string not a character.
For onclick use
onclick='gothere(" + f + ")'
And now, its onto you to write the value. Maybe the issue is because you're not writing the value for the f.
Try inpecting the error. I am sure there won't be anything.
Or try using the attribute field and change it using jQuery.
How about fixing your code ? You are missing the quotes around the value denoted by variable F.
Hence, when variable F is parsed, the function becomes gothere(a) . while a is not a defined variable (but its a value) and hence the error.
Try this !
document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere(\""+f+"\");'> ";
The modified part is onclick='gothere(\""+f+"\");'> "
This should work for you !
function parameter string value image dynamically from JSON. Since item.product_image2 is a URL string, you need to put it in quotes when you call changeImage inside parameter.
My Function Onclick inside pass parameter.
items+='<img src='+item.product_image1+' id="saleDetailDivGetImg">';
items+="<img src="+item.product_image2+" onclick='changeImage(\""+item.product_image2+"\");'>";
My Function
<script type="text/javascript">
function changeImage(img)
{
document.getElementById("saleDetailDivGetImg").src=img;
alert(img);
}
</script>
You need to use single quotation marks for value arguments (see #Nis or #CDspace answer).
Better way to handling dynamic clicks or other events is event binding. See jQuery event binding for example.

How to pass a string as a parameter into a javascript function from a View?

I've just started to work with ASP.NET MVC projects, I have gotten past the basics, but I came across with a problem recently, I can't pass a string as a id from a View.
So far, I've been passing the id to a javascript function like this:
<script>app.init( <%: ViewContext.RouteData.Values["id"].ToString() %>)</script>
This calls the following javascript function:
var app = {};
(function (app) {
var _id;
app.init = function (id) {
_id = id;
}
app.id = function () {
return _id;
}
})(app);
I'm doing this because I need to work with the id to perform operations like submits and ajax calls in javascript (I prefer working with javascript).
So far this has worked with int values, but when I tried to pass a string it fails. For example if I try to access to this url localhost:65097/Device/Edit/D2C02 it shows the following error:
SCRIPT5009: 'D2C02' is undefined
When I check the generated html code, the call to the function looked like this:
<script>app.init(D2C02)</script>
Shouldn't the id be passed as 'D2C02' like a string, instead of just D2C02 like a variable? Because that's what I'm understading the browser thinks the id D2C02 represents. How can I make sure the id value is passed on to the javascript function as a string?
ToString() just converts something to a string - but that's a C# string, not a JS string. So the easiest solution is to add quotes assuming the value can never contain quotes, too:
<script>app.init("<%: ViewContext.RouteData.Values["id"].ToString() %>")</script>
If it may contain quotes you can either perform a simple replacement to backslash-escape them or run the string through a JSON serializer that takes care of turning it into a valid JavaScript string.
Try
app.init("<%......%>");
Otherwise you are just posting in a variable name and not string. The ToString() method in c# doesn't wrap the vale in quotes
The approach I would use is to do something like this, to make things a bit more semantic -- this is overly simplified to demonstrate:
<body>
<input id="myId" type="hidden" value="<%: ViewContext.RouteData.Values["id"].ToString() %>" />
...
<script language="text/javascript">
function getId() {
return document.getElementById("myId").value;
}
</script>
</body>

JavaScript: Sending comma separated string of parameters to a javascript function

I am having a function in javascript as
function add(v1,v2){
var add=v1+v2;
}
Now I am calling this function as below -
write.out(var param="1,2";);
write.out(window[add](param););
Using the above call, it's not working. What it does is it gives the complete string "1,2" as value to the first param(v1) of the function.
Its working if I call the function in following way -
write.out(var param1="1";);
write.out(var param2="2";);
write.out(window[add](param1,param2););
I want to achieve it using the first way where i can send the parameters as a comma separated string of parameters.
Can some one help me out how this can be done...
Thanks!!!
You can make usage of ECMAscripts .apply(), which calls a function and accepts an array of paramters.
window['add'].apply(null, param.split(','));
That way, we execute the add function, setting its context to null (you could also change that if you need) and pass in the two paramters. Since we need an Array, we call split() on the string before.
So basically, the above line is the same as
add(1,2);
Since you're haveing that function in the global context (window), we don't even need to write it that explicitly.
add.apply(null, param.split(','));
will just be fine.

Categories