why JavaScript code changes " ' " character - javascript

When I insert a string into the JavaScript code I get instead the character ' ---> & # x27;
For example-
string= ['orange','apple','mango'] --> ['orange','apple','mango']
cs code-
foreach (var item in _context.Products)
{
if (!string.IsNullOrEmpty(allProducts))
{
allProducts += ",";
}
allProducts += "'" + item.ProductName + "'";
}
AllProducts = "[" + allProducts + "]";
javascript-
var products =#Model.AllProducts;

According to your description, I suggest you could try to use #Html.Raw method to wraps HTML markup from the string representation of an Object in an HtmlString, without HTML-encoding the string representation.
More details, you could refer to below test demo codes:
#section scripts{
<script>
$(function () {
var products = #Html.Raw(Model.AllProducts);
});
</script>
}
Result:

Related

javascript: insert html tag with innerHTML

I have to integrate several html type tags (ex: <div id = "mysection"> <div class = "mycontainer"> <h1> mytitle </h1> </div> </div>) to format data (here "mytitle") output in javascript
So, I have in my HTML <span id="datahere"></span>
and the js i need to edit is :
function Bigdata(title, subtitle, type) {
const mydata = document.getElementById('datahere');
mydata.innerHTML += title + subtitle + (type ? ' <strong>(type is ' + type + ')</strong>' : '') +'<br/>';
}
// element in which the data is initialized, visible in another <span>
const sprit = document.getElementById('sprit');
// when a given message is received
sprit.addEventListener(SpritEvents.MessageSprit, ({ data }) => {
Bigdata('Sprit', data.text, data.type);
// if there are actions, we offer links
if (data.actions) {
var links = '';
for (var i = 0; i < data.actions.length; i++) {
if (i > 0) {
links += ', ';
}
let act = data.actions[i];
links += '<a data-val="' + act.value + '">' + act.title + '</a>';
}
Bigdata('Sprit', links);
}
});
I cannot integrate the tags which must "contain" data (title, subtitle, type) WHITH links if there are actions ...
if I add my tags like this: mydata.innerHTML += '<div id = "mysection"> <div class = "mycontainer"><h1>' + title + '</h1>' + subtitle + (type ? ' <strong>(type =' + type + ')</strong>' : '') +'<br/></div></div>';
that does not surround the whole, the div and the h1 are duplicated (surrounds on one side title, subtitle, type and on the other links).
I'm not used to using pure javascript ... I hope you can help me
I recommend rewriting it using Template literals:
mydata.innerHTML += `<h1>${title}</h1>`;
More on this topic:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
This makes things look much lighter.
Also, it looks like you are not closing the html tags. For example: <div>, needs to be closed with </div>

send data from java to javascript page into a href function

I want to send variable into onclick function, but I did not succeed to get the suitable code.
this is the java code :
for (int i = 0; i < projetList.size(); i++) {
contenuTableHTML.append("<tr>");
contenuTableHTML.append("<td class='width1'><div class='coupe'>" + projetList.get(i).getProjectAbr() + "</div></td>");
contenuTableHTML.append("<td class='width3'><div class='coupe'>" + projetList.get(i).getProjectTkt() + "</div></td>");
List<String> objList = projetList.get(i).getObjectList();
contenuTableHTML.append("<div id='objList' name='objList' value='objList'>");
contenuTableHTML.append("<td class='width3'><div class='coupe'> <a href='#' **onclick='popupFunction(objList)**'>" + projetList.get(i).getObjectList().size() + "</div></td>");
contenuTableHTML.append("</div>");
contenuTableHTML.append("<td class='tableTicketsSummaryTd width3'><div class='coupe'>" + projetList.get(i).getProjectDomain() + "</div></td>");
contenuTableHTML.append("</tr>");
}
As below the javascript code:
function popupFunction(obj) {
objList = document.getElementById(obj);
console.log("objList ",objList);
console.log("obj: ", obj);
var w = window.open("", "", "width=600,height=300");
w.document.write(obj);
w.document.close();
w.focus();
}
I always get objList and obj as null.
The onclick template in html, should be dynamic to send an actual argument (objList) to the javascript function.
You can make use of template literals or dynamic strings while creating your HTML in the following way by adding (template literal) and accessing dynamic elements using ${element} inside the template literal``:
contenuTableHTML.append(`<div id=${objList} name=${objList} value=$[objList}>`);
contenuTableHTML.append(`<td class='width3'><div class='coupe'> <a href='#' onclick='popupFunction(${objList})'>` + projetList.get(i).getObjectList().size() + "</div></td>");
This will allow you to access objList and obj in your javascript function.

hyperlink alternate text replacement

At the moment i've got this code, which replaces a span class whith a hyperlink. The hyperlink includes a abbreviation and the alternate texxt for the hyperlink includes the same abbreviation. Now what i want to do is, to somehow replace the second abbreviation in the alternate text of the hyperlink. So that there isn't "click here to visit + 'name of'abbreviation" but instead an alias. So if the abbreviaton is ggl, the alias should be google. But the hyperlink shouldn't use this alias. Can sb help me? thx
(function($) {
var number = "1234567";
function linkBuilder(abbreviation) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation + "</a>";
}
function linkBuilder2(abbreviation2) {
return "<a href='https://www.test.com/" + abbreviation2 + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation2 + "</a>";
}
jQuery(document).ready(function() {
var fl = $(".first-link");
if (fl.length > 0) {
fl.html(linkBuilder(fl.data("abbreviation")));
}
var sl = $(".second-link");
if (sl.length > 0) {
sl.html(linkBuilder2(sl.data("abbreviation2")));
}
});
})(jQuery);
Here is a working jsfiddle:
https://jsfiddle.net/e7qdx031/1/
linkBuilder() should be re-usable, as kalsowerus mentioned.
Another thing that should be mentioned is that the following code returns a collection of elements, not just a single element.
var fl = $(".first-link");
...
var sl = $(".second-link");
The code you have provided will not function properly if there are multiple .first-link classes on the page. So instead I would iterate over each element using $.each() and run the linkBuilder() function on them individually.
As for the linkBuilder function I would modify it to accept the element object, then read the properties to retrieve alias and name. Full name is something that you seemed to indicate you need, but was not present in the code.
(function($) {
var number = "123456";
function linkBuilder($obj) {
var abbreviation = $obj.data('abbreviation');
var name = $obj.data('name');
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + name + "</a>";
}
jQuery(document).ready(function() {
$('.first-link, .second-link').each(function(index, obj){
$(obj).html(linkBuilder($(obj)));
});
});
})(jQuery);
What you probably want is something like this:
function linkBuilder(abbreviation, alias) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + alias + "</a>";
}
Just pass the display-name you want for your link as the second argument.

Cannot Parse String via JavaScript function

I'm dynamically generate tables row (buttons) using JS- Ajax.when i parse a numeric value removeProduct function return the alert. but i cant get alert if i parse a String. can anyone help me to solve this problem
problem is in this line :
onclick='removeProduct( " + prcode + " )'
how to parse a String via function? (as a JavaScript String)
var single = alldata[i].split("##");
var rows = "";
var prcode = single[1];
rows += "<td><a class='btn' onclick='removeProduct( " + prcode + " )' href='#'><i class='fa fa-trash-o'></i></a></td></tr>";
$(rows).appendTo("#tblproductslist tbody");
Function :
function removeProduct(str) {
alert(str);
}
Thanks in advance!
Because you are trying to pass a string literal, so try to enclose the value in ""
onclick='removeProduct(\"" + prcode + "\")'
Since you are working with jquery, I would recommend you use event delegation to handle event and the data-api to store the data.
You need this:
rows += "<td><a class='btn' onclick='removeProduct( \"" + prcode + "\" )' href='#'><i class='fa fa-trash-o'></i></a></td></tr>";
If "prcode" is a string you must to quote it or it will be treated as (undefined) variable and will trigger an error.
Good luck!

How to create a javascript string in razor

I have seen some posts regarding this topic and a few blogs, but none seem to mention the output I'm getting.
What I want is to generate a google maps map with information on it. Manually entering the information results in the correct information. So that part works.
Where I'm getting stuck is when I'm going to dynamiccaly create the javascript array with the string with the information I want on my map.
The html code I want to get is:
<script type="text/javascript">
var projects = [
['Kantoor 4.1 bestaande bouw', 52.25446, 6.16024700000003, 'Deventer', '', 'adviseurs', 'rating30'],
['School nieuw 4.0', 52.243161, 4.43677860000003, 'Noordwijk', '', 'adviseurs', 'rating30'],
];
Very simple javascript array, which I thought to create with:
<script type="text/javascript">
var projects = [
#foreach (var item in Model)
{
#HttpUtility.JavaScriptStringEncode("['" + item.Gebouwnaam + "', " + item.LocatieLatitude.ToString().Replace(",", ".") + ", " + item.LocatieLongitude.ToString().Replace(",", ".") + ", '" + item.Plaats + "', '" + item.Gebruiksfunctie + "', '" + item.Licentiehouder + "', '" + item.rating + "'],");
}
];
</script>
However this gives me:
<script type="text/javascript">
var projects = [
[\u0027Kantoor 4.1 bestaande bouw\u0027, 52.25446, 6.16024700000003, \u0027Deventer\u0027, \u0027\u0027, \u0027adviseurs\u0027, \u0027rating30\u0027],
[\u0027School nieuw 4.0\u0027, 52.243161, 4.43677860000003, \u0027Noordwijk\u0027, \u0027\u0027, \u0027adviseurs\u0027, \u0027rating30\u0027],
];
</script>
Escaping the single quotes doesn't work.
What am I doing wrong?
Just tried with
<script type="text/javascript">
var projects = [
#Html.Raw("['" + "aaa" + "', '" + "bbb" + "'],")
];
</script>
it worked and showed ...
<script type="text/javascript">
var projects = [
['aaa', 'bbb'],
];
</script>
You don't want to call JavaScriptStringEncode on the entire string, that will also encode your literal indicators (which are being converted to \u0027 in your example). Instead, call it on each item in your array like this:
<script type="text/javascript">
var projects = [
#foreach (var item in Model)
{
String.Format("['{0}',{1},{2},'{3}','{4}','{5}','{6}']",
HttpUtility.JavaScriptStringEncode(item.Gebouwnaam),
HttpUtility.JavaScriptStringEncode(item.LocatieLatitude.ToString().Replace(",", ".")),
HttpUtility.JavaScriptStringEncode(item.LocatieLongitude.ToString().Replace(",", ".")),
HttpUtility.JavaScriptStringEncode(item.Plaats),
HttpUtility.JavaScriptStringEncode(item.Gebruiksfunctie),
HttpUtility.JavaScriptStringEncode(item.Licentiehouder),
HttpUtility.JavaScriptStringEncode(item.rating)
)
}
];
</script>
I believe you could do most of the heavy lifting in .net and leverage Html.Raw to transform the object for you:
#{
var myObj = Model.Select(i => new {
item.Gebouwnaam,
item.LocatieLatitude.ToString().Replace(",", "."),
item.LocatieLongitude.ToString().Replace(",", "."),
item.Plaats,
item.Gebruiksfunctie,
item.Licentiehouder,
item.rating }).ToArray();
}
<script type="text/javascript">
var jsObj = #Html.Raw(Json.Encode(myObj));
</script>
Since it's touched on in this question, HttpUtility.JavaScriptStringEncode() comes in really handy for strings containing newline characters:
#{ var myNetString = "Hi,\r\nMy name is Joe\r\nAnd I work in a button factory"; }
<script type='text/javascript'>
var myJsString = '#HttpUtility.JavaScriptStringEncode(myNetString)';
</script>

Categories