issue passing a value to a function - javascript

EDIT: the 'more' link is built from here:
document.getElementById("elenco_fiveboard").insertAdjacentHTML('beforeend',
"<li>" +
"Titolo: " + valore_comando + " " +
"(<a href='javascript:getInfo("+ valore_comando +");'>" +
"more" + "</a>)" +
"</li>");
So I have to wrap valore_comando with hyphens but I get error trying to write
"(<a href='javascript:getInfo(""+ valore_comando +"");'>" +
or
"(<a href='javascript:getInfo('"+ valore_comando +"');'>" +
Sorry but I am not so strong with JS syntax and I am starting from some code that is not my own.
I have this simple JS function:
getInfo = function(title){
worker.port.postMessage("maggiori_informazioni:" + title);
}
I run it passing to the variable title a value but I always get an error. If title is 'example' then JS try to run
getInfo = function(example)
and I get the error:
Reference Error: example is not defined.
If title has more than one word: 'first example'
then JS will try to run
getInfo = function(first example)
and I get the error:
Syntax error: missing ) after argument list (looking for parentesys
after 'first').
What am I missing here??
This code is part of my first test with webSockets. If you want to see the full code you can open this index page and put a value on the first alert you see. That value is the title that you will see on the dashboard page.
The error can be reproduced trying to hit 'More' after each defined title in dashboard.
Sorry for italian in the site but it's a user requirement.

getInfo having reference to your function. So you can call this by:
getInfo(value);
Use quotes if you are passing string value and if you are passing
integer value you can simply pass.
For instance:
getInfo("Message Title"); //string
getInfo(3); // Integer
DEMO
You can also call like this:
getInfo = function(title){
alert("maggiori_informazioni:" + title);
}("String");
DEMO
Updates:
You can use this:
"(<a href='"+getInfo(valore_comando)+";'>" +

the function has been assigned to getInfo so please call getInfo()
string should be enclosed with ''
So the code should be
getInfo('example')

You're going to have to escape some quotation marks.
"(<a href=\"javascript:getInfo('"+ valore_comando +"');\">" +
The \ character before the quotation marks for the href attribute tells the JavaScript parser that they're part of the string instead of the beginning or end of a string.

The problem is that example is not defined. If you wanted to call the function with example as input it needs either single quotes or double quotes around it. "example" or 'example'.
getInfo("example"); // Works as intended
Another option is to create a variable containing the string, and pass that to the function.
var myVariable = "example";
getInfo(myVariable); // Still works, myVariable is a string with value "example"

Related

JS Events help - when changing a style property

I have a code here that i was supposed to make to change a style property, managed to make it work, but had to look up at the proper way to place the ', the " and the + .
document.getElementById('image').style.backgroundImage="url('" + element.src + "')";
I have no issue understanding how structurally this works, my only question resides on why of the extra ', extra " and extra + inside where you call for the element.src.
originally i did something like this, and it obviously didnt work, why did those ('" + and + "') make the code work...
any help is appreciated
cheers
document.getElementById('image').style.backgroundImage="url(' element.src ')";
Let's analyze everything from your first code segment and that should give you a better understanding:
document.getElementById('image').style.backgroundImage="url('" + element.src + "')";
document is a variable
getElementById is a function, with the string 'image' being a parameter for that function.
style is a property
backgroundImage is a property which must be and must take a string
"url('" is a string
element is a variable, an object in this case, with src being one of its properties.
"')" is a string
The + signs are used to concatenate the string formed from "url('", element.src and "')". In short you are saying, "make a string from "url('", element.src and "')" and assign that string to the property backgroundImage.
Whereas in this:
document.getElementById('image').style.backgroundImage="url(' element.src ')";
The browser has no idea that element.src is a variable and not part of the string, since you enclosed it int double quotes, signaling that everything between the quotes is a string.
element is a variable outside of a string literal, but inside a string literal it is just the word element.
const element = "Hello!";
const first = "start element end";
const second = "start " + element + " end";
console.log({first,second});
Inside of CSS, you have to put your URL inside of quotes or apostrophes, so that has to translate to the javascript as well.
When you call the DOM event it will do this:
Original tag:
<div src="http://example.com/image.png"></div>
after calling the javascript function:
<div style="background-image: url('http://example.com/image.png');" src="http://example.com/image.png"></div>
and because you need to have some sort of quotation in the URL syntax, you have to use a different kind of quotation, such as the '' in this case.
For more reference on the background image style, you can go here: https://www.w3schools.com/css/css_background_image.asp
but to completely answer your question, the + in there is used to say that you want to add something else there, such as another string or a variable.
More information on that here: https://www.w3schools.com/jsref/jsref_operators.asp (you have to scroll down a bit to the string operators section).

Get a string in a variable to create a dynamic link in Javascript

What I am trying to accomplish is to have a map that has a few locations. Whenever users click on each location, a popup will emerge with some information. I am trying to create a dynamic link inside that popup.
Below is my code in Javascript
function parseDescription(message){
var string=""
for(var i in message){
if (i=="CommunityPartner"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="WeitzCECPartner"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="PhoneNumber"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="Website"){
var link = "http://www."+message[i];
string+='<span style="font-weight:bold">'+i+'</span>'+": "+'<a href="{{link}}" >'+link+'</a>'+"<br>"
}
//string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+"<br>"
}
return string;
}
I keep getting this error. I think it's related to the value passed into "a href" :
Request Method: GET
Request URL: http://127.0.0.1:8000/%7B%7Blink%7D%7D
Please help
Instead of using {{link}} in the string, you can try this:
var link = "http://www." + message[i];
string += '<span style="font-weight:bold">' + i + '</span>: ' + link + '<br>';
The following syntax:
{{link}}
is incorrect, because this part was inside a string it was interpreted by the JS engine as a string.
You can use template strings (backticks `) to insert variables as string into another string. For example:
`<span style="font-weight:bold">${i}</span>:<a href="${link}" >${link}</a><br>`;
This example assumes that link and i are both variables which you want to insert dynamically into your string. If you have more questions leave a comment.
I think the problem lies in the {{link}}. Your code looks like native js and not angular or any other framework. Thus, the characters {{}} inside a string do not mean anything. The url that you get is exactly those characters, escaped. Use plain old string concatination to enter your href value.

Escape single quote from last name in jQuery

I have ajax call in my jQuery code with which I am doing lookup with C# web method.
The call works normally most of the time, the user needs to enter last name and it will get all the results for that last name.
The problem happens when user will enter last name with single quote included such as O'leary.
This is the jQuery line I am using:
data: "{selectedAgent: '" + $('#<%=txtAgentNameText.ClientID %>').val() + "',
companyID: '" + $('#<%=ddlCompany.ClientID %>').val() + "'}",
The problem happens with the txtAgentNameText.ClientID value.
It looks like you are passing a JSON string to your jQuery ajax method. Why not just pass a javascript object?
var data = {
selectedAgent:$('#<%=txtAgentNameText.ClientID %>').val(),
companyID: $('#<%=ddlCompany.ClientID %>').val()
};
$.ajax({...data:data...})
Okay so the escape character is \ so you could replace \' or you could change your format so the last name is contained in double quotes! Both ways should suffice

Single quote or double quote in javascript

I always see a write style in javascript but I don't know why code like this.
For example, I have a variable.
var topic = "community";
And when I learned javascript I saw someone coded in jQuery like this, some code in section.
:contains("' + topic + '")
But I think it can code just like this.
:contains(topic)
Or
:contains("topic")
What the differences between above three ?
:contains("topic")
this search for elements that contains "topic" string
where as
var topic = "community";
:contains(topic)
topic here becomes "community"..so it searchs for element that contains "community";
well for this
:contains("' + topic + '")
i guess the code is incomplete..
$('div:contains("' + topic + '")')..; //div for example sake
this becomes
$('div:contains("community")')..; //<-- just to make sure the string is encoded with `""`
:contains("' + topic + '") will look for the string '(VALUE of topic)', including the single quotes.
:contains(topic)
will look for the value of topic, with no surrounding quotes.
:contains("topic")
will look for literally topic.
There is no difference between single quotes and double quotes, both are used to mark an element as a string.
var s = "hello"
var m = 'hello'
m === s // true
the other example refers to escaping a string, in the case of:
contains("' + topic + '")
topic actually references a variable and not a string, therefore the quotes must be escaped in order for the program to get access to the value of the variable. otherwise it would not read the value of the variable topic but simply print the string "topic".
Single quotes vs double quotes usually has to do with whether or not string replacement will happen, but in JS it doesn't matter as far as I know
the difference between the 3 is that the first one is a variable assignment where string replacement can happen. the second one is passing a string as an argument and the third one is passing the variable or constant topic
var topicOne = "Community1";
function write(toOutput) {
document.write(toOutput);
}
write(topicOne);
write("topicOne");
write('topicOne');
so here is what the 3 will output:
Community1
topicOne
topicOne
In PHP however the same code will act differently because the double quote implies string replacement
<?php
$topicOne = "community1";
$topicTwo = "community2$topicOne";
function write($toOutput) {
print $toOutput;
}
write($topicOne);
write("$topicOne");
write('$topicOne');
write($topicTwo);
write("$topicTwo");
write('$topicTwo');
?>
will produce a different output
community1
community1
$topicOne
community2community1
community2community1
$topicTwo
see where the difference is?

Trying to covert a variable into its value within a URL

I'm trying to insert a variable's value into a url, but it's not working; I'm just getting the variable not the value
'myid' and 'verif' are the variables and their values are integers.
This code inserts the url into a hidden field in a form
$('#return').val(http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=myid&packid=1&verif=verif&jcode=xxx111xxx);
How do I write the following url so the variables 'myid' and 'verif' are converted to their values?
Well you are missing quotes so your code would not work at all.
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myid + "&packid=1&verif=" + verif + "&jcode=xxx111xxx");
You should probably use encodeURIComponent()
You need to quotes " " the strings and concat the variables +
Try
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid="+myid+"&packid=1&verif="+verif+"&jcode=xxx111xxx");
JavaScript does not support string interpolation. Try something like this.
myIdVal = encodeURIComponent(myId);
verifVal = encodeURIComponent(verif);
var url = "http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myidVal + "&packid=1&verif=" + verifVal + "&jcode=xxx111xxx";
$('#return').val(url);
A simple string works for me:
given index = 2,
`a.setAttribute("href", "myDirectory/" + index + ".jpg");` links the anchor to
"myDirectory/2.jpg", ie. the file number is taken from variable index.
Not sure if the setAttribute tolerates multiple tokens in its second parameter, but generally, this works.

Categories