could not able to pass string values to javascript function - javascript

When trying to pass String value to the javascript function , Uncaught ReferenceError is thrown on the browser console.
Below is the sample code:
function mySampleTest(myId, comments){
alert("myId " + myId);
alert("comments : " + comments);
}
var myTest = function(value, rowIndex) {
var myId = this.grid.getItem(rowIndex).MY_ID;
var comments = this.grid.getItem(rowIndex).COMMENTS;
return "<img src=<%=request.getContextPath()%>/images/image1.gif width=\"25\" height=\"25\" onClick=\"mySampleTest("+ myId +" , "+comments+")\">";
};
The JavaScript function mySampleTest is being called when the user clicks the image but it throws a JavaScript error when I pass the string comments to mySampleTest function. If I remove the comment parameters and just pass the myId to mySampleTest(..), it works fine.
Please suggest how to pass string values to the JavaScript function.
I tried the below also, but didn't work.
return "<img src=<%=request.getContextPath()%>/images/image1.gif width=\"25\" height=\"25\" onClick=\"mySampleTest("+ myId +" , \'' + comments + '\')\">";

As a professor once told me, much of writing code involves "being the computer".
Consider your function's output for a moment and you should see the issue pretty quickly:
<img src=whatever/your/context/path/is/images/image1.gif
width="25" height="25"
onClick="mySampleTest(12345, this is a comment)">
Your javascript is invalid:
mySampleTest(12345, this is a comment)
It should be:
mySampleTest(12345, 'this is a comment') // <--- notice the quotes
Which would translate all the way back to:
return "<img src=\"<%=request.getContextPath()%>/images/image1.gif\" width=\"25\" height=\"25\" onClick=\"mySampleTest('"+ myId +"' , '"+comments+"')\">";
Not to mention your src attribute really needs quotes.

Related

Passing parameters in a jQuery variable

I've been away from jQuery development and all js in general for about three years. I can not for the life of me remember how this is supposed to work. This has been going on for four days, and I could really use some help.
Can you tell me what I am doing wrong here:
var $imgAll = $(function(f, a) {
'<img src="' + f + ' alt=&quot' + a + '">';
});
var $imgAC = $imgAll('filename1.jpg', 'Some Alt Text');
var $imgBC = $imgAll('filename2.jpg', 'Some Alt Text');
$page.append($imgAC);
I want an output of code for images whose filenames (f) and alt texts (a) are passed using a single function. It looks like Greek at this point because I'm staring at it constantly.
Thanks for any help!
You'll want $imgAll to be a function, not the return value of a call of $. Here is how it could work:
var $imgAll = function(src, alt) {
return $('<img>').attr({src, alt});
}
var $imgAC = $imgAll('https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg', 'Some Alt Text');
$("body").append($imgAC);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note how the call to attr avoids building the attribute strings yourself, and thereby the potential problems with characters that need escaping. Also, by naming the function parameters as the attribute names (src and alt) you can use the short object literal notation. You could even use an arrow function expression:
const $imgAll = (src, alt) => $('<img>').attr({src, alt});

How to invoke javascript in WebView Windows 10 UWP?

I am trying to load a javascript in WebView to do some calculations and get the output in a string. I tried to use following code
string htmlFragment = "<html><head><script type='text/javascript'>" +
"function doubleIt(incoming){ " +
" var intIncoming = parseInt(incoming, 10);" +
" var doubled = intIncoming * 2;" +
" document.body.style.fontSize= doubled.toString() + 'px';" +
" return doubled.toString());" +
"};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
htmlView.NavigateToString(htmlFragment);
htmlView.LoadCompleted += async(s1,e1) =>
{
string result = await htmlView.InvokeScriptAsync("eval", new string[] { "doubleIt(25)" });
Debug.WriteLine(result);
};
Update
I am able to load simple javascript easily now based on help provided in the answer. But now I am facing issues when there is more than one function in javascript, I am getting an exception. I am trying the following code
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return 10;};" +
"function b(){return 20;};" +
"function c(){return 30;};" +
"return (a()*b()*c());" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
Please suggest.
The documentation for this feature is really poor. It took me some time to figure out how to invoke Javascript in UWP WebView
When you first look at the function call webView.InvokeScriptAsync(string,string[]) your initial reaction is that they want the function name as the first parameter and then the function paramaeters as the string array. (mainly because the MSDN documentation says this)
Parameters
scriptName
Type: System.String [.NET] | Platform::String [C++]
The name of the script function to invoke.
arguments
Type: System.String[]
[.NET] | Platform::Array [C++]
A string array that
packages arguments to the script function.
HOWEVER, this is wrong and will lead to hours of head banging. REALLY, what they want is the word "eval" in the first parameter and then a string array of functions, and or commands you wish to eval
var value = await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
Having worked with Microsoft APIs for a few years now I am convinced that this is not the intended way of consuming this function and is a bit of a hack. Unfortunately if you want to consume JavaScript this is the only way that I know that works currently.
Anthony,
Try to check your own suggestion:
await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
or:
await webViewer.InvokeScriptAsync(functionName, new string[]{ functionParameters });
The same as Microsoft suggests, just you are limiting a function name by one ("eval") - not necessary. Trust me, you can use any function name, as I am now with UWP and before with windows phone hybrid apps.
The question is already 4 years old, but I'm coming to see why you were getting an empty string as a result.
In your example, the functions in JavaScript return integers while the expected value is of type string.
By modifying these functions and returning a string like this:
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return '10';};" +
"function b(){return '20';};" +
"function c(){return '30';};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
We get the good result on the way back.

Unable to concanate String+Variable+String in Javascript

I am trying to dynamically have my javascript look for an element ID in the DOM.
I am currently using this
var string = "retail";
document.getElementById('markup_'+string+'_percentage').value=z.toFixed(2)+"%";
Where the variable "string" has a value like "retail"
This I thought would give a concatenated string of "markup_retail_percentage".
However it actually gives this as an error message:
document.getElementById("markup_"+string+"_percentage") is null
I have tried also using the "." and " * " operators.
One of my html elements
<input type="text" id="markup_retail_percentage" size="5" name="markup_retail_percentage" value="" readonly />
SOLUTION!!!!
//using a new variable name to be passed to function
function percentage(elementid)
{
elementid = "markup_" + elementid;
elementid = elementid + "_percentage";
document.getElementById(elementid).value = "a value";
}
I see two^w three^w four possibilities:
string doesn't contain what you think it does
you should have an underscore before percentage.
the specified element really doesn't exist! (thanks #jAndy)
it does, but the DOM isn't ready yet (thanks #Yoshi)
It looks like you are missing an underscore ahead of percentage
document.getElementById('markup_'+ string +'percentage')
I think you want
document.getElementById('markup_'+ string +'_percentage')
If you run this code before the Document has finished loading, your markup will not have been fully parsed and the Element with that id will not be accessible using DOM methods.
Solution:
function percentage(elementid)
{
elementid = "markup_" + elementid;
elementid = elementid + "_percentage";
document.getElementById(elementid).value = "a value";
}
I dont know why its working:
-Could be concatenation problem , not allowed to use multiple " + " operators?
-Change variable name ?
But it is working now, so thanks to all!

Javascript Error: 'missing ) after argument list"

I am making an image for my webpage through javascript like so:
photoHTMLString = '<li class = "SliderPhoto"><img src = "' + ImageArray[x].src_small + '" size = "thumb" onclick = "ShowImagePopUP(' + ImageArray[x].src_big + ')" class = "FacebookSliderPhoto"/></li>';
Whenever I try and click a photo go into ShowImagePopUP I get this error:
missing ) after argument list
[Break On This Error] ShowImagePopUp(http://a8.sph...389_84095143389_5917147_2636303_n.jpg)
It doesn't look like I am missing any ')'s so I am lost on the error.
Any suggestions?
You need to wrap the contents of ShowImagePopUP in quotes:
"ShowImagePopUp(\'' + ImageArray[x].src_big + '\')"
Which should render as:
ShowImagePopUp('http://a8.sph...389_84095143389_5917147_2636303_n.jpg')
^ note the quote here
Example: http://jsfiddle.net/V23J6/1/
try
photoHTMLString = '<li class = "SliderPhoto"><img src = "'
+ ImageArray[x].src_small
+ '" size = "thumb" onclick = "ShowImagePopUP(\"'
+ ImageArray[x].src_big + '\")" class = "FacebookSliderPhoto"/></li>';
should do the trick and solve your problem leaving intact the uglyness of you code
A function like this one should be a bit readable and ready to use...
function slideElement(image){
var li=document.createElement('li');
var img=document.createElement('img');
li.appendChild(img);
li.setAttribute('class','SliderPhoto');
img.setAttribute('class','FacebookSliderPhoto');
img.setAttribute('size', 'thumb');
img.setAttribute('src', image.src_small);
img.setAttribute('onclick', function(){showImagePopUP(image.src_big);});
return li;
}
The value in ImageArray[x].src_big needs to be quoted.
Try to avoid building HTML by mashing strings together. Using a DOM builder gives code that is much easier to debug.
You'd probably be better off writing this so the function computes the large URI based on the small URI rather than having it hard coded.
Here's some general advice, build up the strings into intermediate variables and then assemble it at the end. You can then use the debugger to find out where you're getting your ' or "s unbalanced. When you have it all built you can coalesce it into a single line if you want or leave it with the intermediate variables.

jQuery can't get a good formatted Id

I have a problem with this fonction:
function test(value){
var id = "'" + value + "'";
$(id).remove();
}
It gets an "Id", add simple quotes and then call the remove function.
The "value" is a generated id by php. For example, I can have:
$var = "$the_id";
When the "test" function is triggered by a click, I get te following error:
Uncaught Syntax error, unrecognized expression: ''
I thought it's because the function cannot get the id. But when I insert an alert in the function ( alert (id) ), it returns the right "id" with the good format ( '#the_id').
How can solve this problem?
Thank you,
regards.
Assuming the value argument to your function is the id then you want to change your function to:
function test(value){
var id = "#" + value;
$(id).remove();
}
If the value is already a string of "#the_id" then you don't need to quote it.

Categories