how do I dynamically add link text to a href in javascript? - javascript

I have this javascript code. When it renders it shows quotes around the text of the link rather than just the text. What is the syntax to properly concatinate the link text? My quotes are messed up but I cannot figure it out.
var link = "<a id=\"myLink\" href=\"\" target=\"_blank\">\"" + text + "\"</a>";

Looks like you had extra quotes. You do not need to escape those around + text +. The following should work:
var link = "<a id=\"myLink\" href=\"\" target=\"_blank\">" + text + "</a>";
I prefer single quotes:
var link = '<a id="myLink" href="" target="_blank">' + text + '</a>';
When using the + operator to concatenate a variable and a string, you just have to keep track of opening and closing quotes. It can get tricky!
Similar example:
var str1 = "string";
var str2 = "This is how to concatenate a " + str1 + ".";
console.log(str2);

Do this
var link = "<a id=\"myLink\" href=\"\" target=\"_blank\">" + text + "</a>";
Do not escape the quote before '+ text +'

Check this code :
const text = 'My awesome link'
const link = "<a href='http://google.com' target='blank'>" + text + "</a>
console.log(link);

Related

Javascript var in string

So I have this code and would like to know how I could go ahead to put my javascript var into this string. I cannot seem to make a working code for myself.
For the image source i want picture.value to be in there. I have tried different solutions but have not managed to work it out myself. All help is greatly appreciated
var text = "<img src="">
I have currently been trying var text = "<img src=" + picture.value +">
but that doesn't seem to work for me.
You cannot use " & ' this together unless you escape it with a \.
var text = '<img src="' + picture.value + '">'
OR
var text = "<img src=\"" + "Hi" + "\">"
Try using ES6 new feature called Template literals (using quote). It is more cleaner and simpler.
var picture = {'value':'test-src-location'};
var text = `<img src="${ picture.value }">`;
console.log(text);
Assuming your picture.value is not empty.
var text = '<img src=' + picture.value + '>';
Example: https://jsfiddle.net/no293etL/

The value passed in onclick() attribute of dynamically generated anchor tag is ending with first space

have to pass two parameters in the onlclick() of anchor tag which is being generated from code behind(c#).if there is any space in the first parameter the onclick() is being closed with double quotes. It is not taking the complete value.
LiteralControl lc2 = new LiteralControl();
lc2.Text = String.Format("<a href='#' class='easyui-linkbutton' " + #"onclick=addTab(" + childMenus[j].MenuName.ToString() + "," + url + #")> " + #" Setting " + #" </a>");
screenshot of browser's inspect element :
the value of first parameter is "Exam and course setting" but it is ending after "Exam" at first space. It is assuming space as ending.
I've changed the controls in my lc2 string to use string variables to demonstrate how you can create the escaped html:
string MenuName = "Exam and course setting";
string url = "http://stackoverflow.com";
var lc2 = "<a href='#' class='easyui-linkbutton' " + #"onclick='addTab(""" + MenuName.ToString() + #""",""" + url + #""")'>" + #"Setting" + #"</a>";
which will generate the following:
<a href='#' class='easyui-linkbutton' onclick='addTab("Exam and course setting","http://stackoverflow.com")'>Setting</a>
Don't forget to HTMLEncode any text from the controls if they contain single or double quotes. You can replace with ' for ' and
" for ".

Use of URLs in Javascript

I would like to prettify this URL in the output, how can i do that?
var msg = beasts[loc.beast_id] + "! Left "+dateFormat(timeToDespawn, "MM:ss")+" Link " + " https://www.google.com/maps/dir/Current+Location/"+loc.latitude+","+loc.longitude+" ";
The word "Link" should directly link to this:
https://www.google.com/maps/dir/Current+Location/"+loc.latitude+","+loc.longitude+"
is this possible, and how?
Thanks in advance!
Assuming you want to output to HTML, you would create your link like this:
var msg = "<a href='https://www.google.com/maps/dir/Current+Location/" + String(loc.latitude) + "," + String(loc.longitude) + "'>Link</a>";
You would use this to output it to your HTML page:
$('#foo').html(msg);
Working jsFiddle.

Javascript string HTML composition

I have this function that I use as a Custom Formatter in a JqGrid for ASP.NET WebForm
function formatLink(cellValue, options, rowObject) {
var res = cellValue.split(" - ");
var newLink = "";
var value = rowObject['Filter'];
var link = '<a class=\"clickCell\" href=\"#\" OnClick=\"CellClicked(\'value\')\">' + res[0] + '</a> - ' + res[1];
newLink = link.replace("value", value).replace("'", "\'");
return newLink;
}
the returned link does not work.
Here is an example:
<a onclick="CellClicked('vpd.esercizio = '2011-2012'')" href="#" class="clickCell">3</a>
As you can see, the var value contains string with quote. I will use its content to compose sql where condition.
Can you help me get things work?
Why don't you simply do
value.replace("'","\\'")
var link = '<a class="clickCell" href="#" OnClick="CellClicked('+value+')">' + res[0] + '</a> - ' + res[1];
?
With that replace you should be fine. I also removed some unnecesary back slashes because you can use double quotes inside simple quotes.
document.write(' "" '); returns ""

Unable to pass the array value in the Hyperlink

Below is the code that I am using with Jquery to pass a value when a hyperlink is selected on sharepoint disp form.
for(var i=0;i<retval.length;i++)
{
strHTML = strHTML + "<a href='url.aspx?ID= '+retval[i]+' &Source= url'>" + retval[i] + "</a>";
strHTML = strHTML + " ";
}
strHTML = strHTML + "</div>";
$("textarea[Title='Test']").closest("span").find("iframe[Title='Rich Text Editor']").contents().find("body").html(strHTML);
Its unable to read the value in retval[i], its breaking right at ID. Is the syntax wrong?
If you want the variable to evaluate, it needs to be outside of the quotes (as you did with the actual hyperlink's text):
strHTML = strHTML + "<a href='url.aspx?ID=" + retval[i] + "&source=url ...";
However, I would look at using encodeURIComponent before placing it within a URL:
strHTML = strHTML + "<a href='url.aspx?ID=" + encodeURIComponent(retval[i]) + "&source=url ...";
Also, try to avoid including spaces in the URL (make sure the variable, equal sign (=) and value are close together). Also, given the href attribute's value is surrounded by single quotes (') you want to avoid using them in the middle of the URL (e.g. don't surround the ID's value within the URL with ').
var id = 'foo';
var bad = "<a href='target.aspx?ID='"+id+"''>Invalid</a>";
// bad = <a href="target.aspx?ID='foo''>Invalid</a>
// note that the single quotes now interfere
var good = "<a href='target.aspx?ID="+id+"'>Valid</a>";
// good = "<a href='target.aspx?ID=foo'>Valid</a>";
// note now that the quotes align and the value is acceptable
A bit more readable:
var atag = "url.aspx?ID="+encodeURIComponenet(retval[i])+"&Source=url";
strHTML = strHTML + "<a href='"+atag+"'>" + retval[i] + "</a> ";
Hope this helps!
Since you have the double quotes surrounding the entire string:
"<a href='url.aspx?ID= '+retval[i]+' &Source= url'>"
Its reading the +reval[i]+ as part of the string, what you want to do differentiate between string and command. You will need to use the double quote to end the string and add your command. You will need to change the above to:
"<a href='url.aspx?ID=" + retval[i] + "&Source=url'>"

Categories

Resources