JavaScript Undefined issue from a JSON string - javascript

I am trying to add data from a JSON string to a table in the following way:
tr = "<tr><td>" + data[i]["code"] + "</td><td>" + data[i]["codeDesc"] + "</td></tr>";
But on execution I get:
undefined<tr><td>C1713</td><td>ANCHOR/SCREW OPPOSING BN-TO-BN/SOFT TISSUE-TO-BN</td>
I don't understand why this 'undefined' is getting appended.

what you use jquery or pure javascript ?
if you use jquery you should write something like
$("yourId").html(tr);
if you use pure javascript must be
document.getElementById("yourId").innerHtml = tr;
if you don't specificate this call undefined because the javascript don't know if this is only text or html tag .

Related

Use Go to read a file for use in javascript rendering

I have seen many articles about Go Arrays being used with Javascript but I am trying to do something a little different. I want to read a configuration file using Go, since it has access to the server side, and use it in a javascript function that will be rendered with the template. This is to avoid hard coding values in the JavaScript:
I want to change this:
javaString += "function isValidPrefix() {"
javaString += "forbidden_prefixes = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\" ];"
... more javascript ...
javaString += "}"
to something that puts the prefixes in a file, so that I don't have to recompile every time I want to add a prefix.
So I tried this:
var configArr []string
configArr = LoadFile("/conf.dat")
javaString += "forbidden_prefixes = [];"
for _, eachline := range configArr {
javaString += "forbidden_prefixes.push(\" + eachline + \");"
fmt.Println(eachline)
}
eachLine prints out correctly in the for loop but forbidden_prefixes contains one element + eachLine + which I am assuming is a syntax error but even if I try to retrieve the DOM element's value to check it against, the web console says the element doesn't exist. Everything worked fine with the hardcoded values. Am I doing something wrong or is it simply just not possible?
You are building a string using literals, without using the variable you intended to use. Try this:
javaString += fmt.Sprintf("forbidden_prefixes.push(\"%s\");",eachline)
The issue indeed comes from your syntax. You escaped the quotes so the + operators are actually part of the string. Here are two possible solutions:
javaString += "forbidden_prefixes.push(\"" + eachline + "\");"
Or
javaString += fmt.Sprintf("forbidden_prefixes.push(%q);", eachline)
%q adds quotes around the value it's replaced with.

Blazor, get Input value from Javascript created DOM Element

I have been working with Blazor quite a bit (https://blazorboilerplate.com) but I have a bit of a issue that has stumped me tonight with adding some custom D3 code to my blazor pages. The D3 / Javascript code creates several DOM input elements and I wish to retrieve the values of these created elements so I can save a DTO to my database with those values. How can I do this and what is the most efficient way? Should I just create a JSInterop method to return the input values?
domInput.attr("#ref", function (d3) {return d3.key});
I tried creating "#ref" attributes so I could use the ElementReference but D3 errors when I try to append an attribute that begins with '#'
After some more research from Mr. Magoo's comment you cannot interact with DOM that was / is created by JS and / or modified by JS. To get around this though you can create a JS function to return your data. So I created a helper method that returns a JSON string of my data. Then I call that JS from my Blazor code and use Newtonsoft to Deserialize it. The d3 code could easily be changed to vanilla javascript or JQuery to get the DOM elements value / innerHTML.
Blazor Code
var data = await JsRuntime.InvokeAsync<string>("JsInteropFunc", null);
dataDto = Newtonsoft.Json.JsonConvert.DeserializeObject<DataObjectDto>
(data);
Javascript Code, this case uses d3 to get the DOM Element with a class name to get the text form the DOM element:
window.JsInteropFunc = function() {
function cleanStr(data){
return data.replace("$","").replace(",","").replace("%","");
}
return '{ totalSales: "' + cleanStr(d3.select(".totalSales").text()) + '"' +
', annualSales: "' + cleanStr(d3.select(".annualSales").text()) + '"' +
', profitMargin: "' + cleanStr(d3.select(".profitMargin").text()) + '"' +
'}' ;
},

Why do I get JavaScript runtime error: Expected ')' when I'm adding a client-side event to a dynamically generated button?

I am dynamically generating a aspxbutton and attaching a client-side event to it.
When the following code is executed,
Dim path As String = HttpRuntime.AppDomainAppVirtualPath + "/PDF.aspx"
button.ClientSideEvents.Click = "window.open('" + path + "', '_blank');"
I get the following javascript error
JavaScript runtime error: Expected ')'
And i'm unsure why. Appreciate the help!
It looks like it's expecting a ) and isn't getting it. It's probably because the single and double quotes are getting messed up here:
button.ClientSideEvents.Click = "window.open('" + path + "', '_blank');"
Try escaping the single quotes using \ like so:
button.ClientSideEvents.Click = "window.open(\'" + path + "\', \'_blank\');"

Convert php's htmlspecialchars() with javascript

I have a variable written from PHP into my javascript (using json_encode), that looks a little like this:
mappoints[x]['about'] = 'Administrator: Foo Barlt;br />Telephone: 555-4202<br />Email: bert#hotmail.com<br />Website: www.domain.com'
That I am using for a google maps map point. Using the json_encode seems to be very picky about what characters I can and cannot enter into it, so i am wondering how I can convert those special html characters into real html characters using javascript?
update
The way i am building my variable is:
var description = "<h3 style='margin: 0; padding: 0;'>" + mappoints[x]['name'] + "</h3><b>Director:</b> " + mappoints[x]['director'] + "<br/>" + mappoints[x]['about'];
The HTML in the varaible is all fine, until I add the about index. No function I have attached or tried yet seems to give me proper HTML.
You can use the dom to decode those entities for you.
mappoints[x]['about'] = 'Administrator: Foo Barlt;br />Telephone: 555-4202<br />Email: bert#hotmail.com<br />Website: www.domain.com'
mappoints[x]['about'] = $('<div/>').append(mappoints[x]['about']).text();
http://jsfiddle.net/5FTCX/
Basically when you add the html to the dom it will show the entities as the characters they represent, using .text() you can receive the data back as you'd see it in the browser as text, not html with the entities. If you want back the html you can use .html() e.g..
Would it be okay with :
return mystring.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
From here : Convert special characters to HTML in Javascript
Just because #Musa's idea was great but needed some re-interpreting on my side, I wish to post a quick function here, that will handle htmlspecialchars great, based on #Musa's design :
function htmlspecialchars_decode(string) {
$('body').append("<span style='display:none;visibility:hidden;' id='tempText'>" + string + "</span>");
var result = $('#tempText').text();
$('#tempText').remove();
return result;
};
try this
decodeURIComponent(str) or `unescape(str)` or `decodeURI(str)`

getElementById to get the ID of the element

Im currently using JSP and need to get the a cell in a table.
the following is of course in a for loop in javascript:
var cell=document.getElementById('cell_' + newRow + ',' + i);
now on variable cell I need to get the ID. Any ideas how to do that?
if i do alert(cell); then it returns this value: [object HTMLTableCellElement]
Thanks
alert(cell.id);
should work. You can find whole DOM Element attribute and method reference here:
http://www.javascriptkit.com/domref/elementproperties.shtml
try debuging it and use Watch on the newRow parameter.
as far as I know its var cell=document.getElementById('cell_' + newRow.id + ',' + i);

Categories