Uncaught syntaxerror: Unexpected Identifier (Javascript, asp.net mvc, cshtml) - javascript

So the error I am receiving is when I click the remove button on the dynamically created html, which is meant to call the remove method at the bottom and pass the arguments. The passing of the object as an argument is where I am running into the problems..
function addMarkerToList(args) {
var object = args;
var camera = args.id;
var test = selectedCameras.indexOf(args.id);
var noOfCamerasAllowed = #Model.usersName.CamerasSelectable;
if (selectedCameras.length < noOfCamerasAllowed) {
if (test > -1) {
alert("Camera already in list");
} else
{
selectedCameras.push(args.id);
var outputString = "";
for (i = 0; i<selectedCameras.length; i++) {
outputString += selectedCameras[i] + ",";
}
//$("#cameraSelectedList").append("<p id=" + args.id + ">" + args.id + "</p>");
$("#cameraSelectedList").append(
"<div id = " + camera + " class=\"col-md-12\">" +
"<div class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 user-item\">" +
"<div class=\"user-container\">" +
"<a class=\"user-avatar\"><i class=\"glyphicon glyphicon-facetime-video\" style=\"color: #ed1c24; font-size: 36px;\"></i></a>" +
"<p class=\"user-name\">" +
"<span>Camera</span>" +
This is where I think the issue is being caused:
"<input type=\"button\" value=\"Remove\" onclick=\"removeMarkerFromList(" + object + ")\"/>" +
"</p>" +
"</div>" +
"</div>");
The directly above section is where the error is being caused, I think by how I am passing the args called (object) in the input button back the the remove method below..
if (check === 0) {
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 1;
lastAddedId = (camera + ".2");
} else {
//alert("This is the last added id: " + lastAddedId);
document.getElementById(lastAddedId).remove();
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 0;
lastAddedId = (camera + ".2");
}
}
} else {
alert("You have added the maximum number of cameras");
}
}
//Removing objects by right clicking the marker
function removeMarkerFromList(args) {
var camera = args.id;
alert(camera);
var test = selectedCameras.indexOf(camera);
if (test > -1) {
document.getElementById(camera).remove();
selectedCameras.splice(test, 1);
alert("Camera removed from list");
} else {
alert("Camera not in list");
}
var outputString = "";
for (i = 0; i<selectedCameras.length; i++) {
outputString += selectedCameras[i] + ",";
}
document.getElementById(lastAddedId).remove();
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 1;
lastAddedId = (camera + ".2");
}

You're concatenating your object into a string, which probably gives you something like
onclick="removeMarkerFromList([Object object])"
You can use an id (string or number) instead and retrieve your object afterwards:
"onclick=\"removeMarkerFromList(" + object.id + ")\"/>"
You can also stringify your object:
"onclick=\"removeMarkerFromList(" + JSON.stringify(object) + ")\"/>"

I managed to solve the issue by using object manipulation before passing the object to my method.
Thank you everyone for your assistance!

In ASP.NET/MVC/.NET Core project if you are facing this issue, sometimes this might be due to cache storage refresh not happening. In my instance, I had a Redis server running and it needed a manual restart. Go to Task Manager-> Services tab and see the server you are running and restart it manually( Redis server: Memurai in case if you are using windows).

Related

How to get rid of many IFs and make a system to differ elements?

In this piece of code you can see a JSON request that fetches some data. I need some help to check certain opportunities of minimizing the code and getting iterations with FOR instead of many IFs. Also, it would be nice if you advise anything on the differentiation system (how to make elements differ from each other)
<script type="text/javascript">
function deleteRow0() {
$('p.row0').remove();
};
function deleteRow1() {
$('p.row1').remove();
};
function deleteRow2() {
$('p.row2').remove();
};
function deleteRow3() {
$('p.row3').remove();
};
function deleteRow4() {
$('p.row4').remove();
};
</script>
<script type="text/javascript">
function hello2() {
//GETTING JSON INFO
$.getJSON("https://rawgit.com/Varinetz/e6cbadec972e76a340c41a65fcc2a6b3/raw/90191826a3bac2ff0761040ed1d95c59f14eaf26/frontend_test_table.json", function(json) {
$('#table-cars').css("display", "grid");
for (let counter = 0; counter < json.length; counter++) {
$('#table-cars').append("<p class='row" + counter +" main-text'>" + json[counter].title + "<br/>" + "<span class='sub-text'>" + json[counter].description + "</span>" + "</p>"
+ "<p class='row" + counter +" main-text'>" + json[counter].year + "</p>"
+ "<p id='color" + [counter] + "' class='row" + counter +" main-text'>" + json[counter].color + "</p>"
+ "<p id='status" + [counter] + "' class='row" + counter +" main-text'>" + json[counter].status + "</p>"
+ "<p class='row" + counter +" main-text'>" + json[counter].price + " руб." + "</p>"
+ "<p class='row" + counter +" main-text'>" + "<button class='delete' onclick='deleteRow" + [counter] + "()'>Удалить</button>" + "</p>");
// COLOR TEXT REPLACEMENT
if ($('p#color0').text("red")){
$('p#color0').text("").append("<img src='red.png'>");
}
if ($('p#color1').text("white")) {
$('p#color1').text("").append("<img src='white.png'>");
}
if ($('p#color2').text("black")) {
$('p#color2').text("").append("<img src='black.png'>");
}
if ($('p#color3').text("green")) {
$('p#color3').text("").append("<img src='green.png'>");
}
if ($('p#color4').text("grey")) {
$('p#color4').text("").append("<img src='grey.png'>");
}
// STATUS TEXT REPLACEMENT
if ($('p#status0').text("pednding")) {
$('p#status0').text("").append("Ожидается");
}
if ($('p#status1').text("out_of_stock")) {
$('p#status1').text("").append("Нет в наличии");
}
if ($('p#status2').text("in_stock")) {
$('p#status2').text("").append("В наличии");
}
if ($('p#status3').text("out_of_stock")) {
$('p#status3').text("").append("Нет в наличии");
}
if ($('p#status4').text("in_stock")) {
$('p#status4').text("").append("В наличии");
}
}
});
}
</script>
I expect this to be something like:
1) Iteration: For each p.row(i) {
compare it to many color (json.color)};
2) Any suggestion on differentiation system (i.e. changes in the FOR section, so it gives something easier to work with, not just simple p.row(n)). Of course, if it is possible.
I'm not going to rewrite the entire script, but in principle it would be something like this:
for (i = 0; i < 5; i++) {
var colors = ["red", "white", "black", "green", "grey"];
if ($('p#color' + i).text() == colors[i]){
$('p#color' + i).text("").append("<img src='" + colors[i] + ".png'>");
}
}
#Evik Ghazarian has a quality solution for the Text Translation portion of your script. Since this is the accepted answer, he allowed me to copy his solution so that the answers would be together:
function getTranslate(input) {
var inputMap = {
"pednding": "Ожидается",
"out_of_stock": "Нет в наличии",
"in_stock": "В наличии"
}
var defaultCode = input;
return inputMap[input] || defaultCode;
}
for (let i = 0; i < 5 , i ++){
var text = $("p#status"+i).text();
$("p#status"+i).text("").append(getTranslate(text));
}
Dynamic Iteration Counters
#Barmar mentioned in the comments below that the for loops that set a max iteration via i < 5 should actually be rewritten dynamically. I'll leave it to the OP to decide the best way to do this, but a good example might be something like i < json.length as used in the OP's original for loop.
First of all your code won't work because you are setting the text rather than comparing it. Second, you don't need to compare: just set the img src to text. Like below:
REMEMBER THIS IS FOR COLOR TEXT REPLACEMENT PART OF YOUR QUESTION
for (let i = 0; i < 5 , i ++){
let color = $("p#color"+i).text() + ".png";
$("p#color"+i).text("").append("<img src=" + color + ">");
}
FOR TEXT TRANSLATION YOU CAN USE:
function getTranslate(input) {
var inputMap = {
"pednding": "Ожидается",
"out_of_stock": "Нет в наличии",
"in_stock": "В наличии"
}
var defaultCode = input;
return inputMap[input] || defaultCode;
}
for (let i = 0; i < 5 , i ++){
var text = $("p#status"+i).text();
$("p#status"+i).text("").append(getTranslate(text));
}

make pagination in papaya dicom viewer slices using javascript

i'm using papaya API from github
In this papaya dicom viewer, I want to integrate few things.
One is pagination. if i try to edit this API, I'm getting error
What i want:-
In the papaya viewer NEXT, PREV is working fine but I want to make
On click to FIRST and the LAST slice moving.
And also the pagination will be 1,2,3,4...If click ONE first slice
should appear.
Advance thanks
After download Papaya medical research image viewer, choose to work test folder file, So that you can understand how papaya Dicom viewer working.
Step 1:-
In the js folder open constants.js file and create the constants
var MOVE_TO_FIRST_SLICE = "move-to-first-slice",
MOVE_TO_LAST_SLICE = "move-to-last-slice";
PAGINATION_LIST = "pagination-list";
Step2:-
Now open the viewer.js, create this on click functions FIRST, LAST and 1,2,3... slices(data-value).
$(this.container.containerHtml.find("#" + MOVE_TO_FIRST_SLICE + this.container.containerIndex)).click(function () {
viewer.firstLastSlice(false);
});
$(this.container.containerHtml.find("#" + MOVE_TO_LAST_SLICE + this.container.containerIndex)).click(function () {
viewer.firstLastSlice(true)
});
$(this.container.containerHtml.find("." + PAGINATION_LIST + this.container.containerIndex)).click(function () {
var id = $(this).data('value');
viewer.pagination(id);
});
Step 3:-
And open the main.js and create the elements
papaya.Container.fillContainerHTML = function (containerHTML, isDefault, params, replaceIndex) {
containerHTML.append("<button type='button' id='"+ (MOVE_TO_FIRST_SLICE + index) + "' class='" + MOVE_TO_FIRST_SLICE + "'>First</button> ");
containerHTML.append("<button type='button' id='"+ (PAPAYA_CONTROL_MAIN_INCREMENT_BUTTON_CSS + index) + "' class='" + PAPAYA_CONTROL_MAIN_INCREMENT_BUTTON_CSS + "'><</button> ");
var max = 23;
var slice;
for(slice=1; slice<=max; slice++){
containerHTML.append("<button id='"+ (PAGINATION_LIST + index) +"' class='"+ (PAGINATION_LIST + index) + "' data-value='" + slice + "' OnClick(" + slice +") >" + slice + "</button>");
}
containerHTML.append("<button id='"+ (PAPAYA_CONTROL_MAIN_DECREMENT_BUTTON_CSS + index) + "' class='" + PAPAYA_CONTROL_MAIN_DECREMENT_BUTTON_CSS + "'>></button> ");
containerHTML.append("<button type='button' id='"+ (MOVE_TO_LAST_SLICE + index) + "' class='" + MOVE_TO_LAST_SLICE + "'>Last</button> ");
containerHTML.append("<button type='button' id='"+ (GET_MAX_VALUE + index) + "' class='" + GET_MAX_VALUE + index + "'>TesT</button> ");
}
Step4:-
The below functions are important to move slices viewer.js
//pagination 1,2,3
papaya.viewer.Viewer.prototype.pagination = function (id, paginationList) {
var max = this.volume.header.imageDimensions.zDim;
//console.log(id);
this.currentCoord.z = id;
this.gotoCoordinate(this.currentCoord);
};
// firstLastSlice
papaya.viewer.Viewer.prototype.firstLastSlice = function (flSlice, degree) {
var max = this.volume.header.imageDimensions.zDim;
if (degree === undefined) {
degree = 0;
}
if (flSlice) {
this.currentCoord.z = max;
} else {
this.currentCoord.z = 0;
}
this.gotoCoordinate(this.currentCoord);
};
Explanation
viewer.js calculated total slices this.volume.header.imageDimensions.zDim; and stored the total count in Max variable. If the this.currentCoord.z = max; It will go to last slice else, If the this.currentCoord.z = 0; It will move to first slice.
In pagination on click to passed data-value to viewer.js pagination function and if this.currentCoord.z = id(id <=> data-value ) It will move to particular slice.
After click using this function this.gotoCoordinate(this.currentCoord); the slice will move.

Leaflet: sort and edit geojson data in a table with if-statements

I'm having trouble with displaying json data in a table. I am working on a map that shows data wich is directly exported as a geojson file from Openstreetmap via overpass-turbo.eu. This means that every point has different features. I want to show as much information in the popup as possible, but keep unessesary information out of the table, plus I want the links to be clickable. This is my code so far, that provides a basic table view of each point. Here is a demo: http://stefang.cepheus.uberspace.de/stackexample/
function everyPoint (feature, layer){
var popupcontent = [];
for (var prop in feature.properties) {
popupcontent.push("<tr><td>" +prop + ": </td><td>" + feature.properties[prop].replace(";", ", ") + "</td></tr>");
}
var innerTable = popupcontent.join("");
layer.bindPopup(
"<h1>" +feature.properties.name +"</h1>"
+"<table>" +innerTable + "</table>"
+"<p> Old or outdated data? Change it on <a href='http://openstreetmap.org/" +feature.id +"'> on openstreetmap.org</a>.</p>"
);
};
L.geoJson(karlsruhe, {
onEachFeature: everyPoint
}).addTo(map);
I want to do three things here:
Hide unnessesary data, basically #ID, Shop:Farm
Switch URLs to hyperlinks, mainly website and contact.website
Show everything else as a text in the table
I tried to solve this with a simple if-statement, but only the else block runs:
var popupcontent = [];
for (var prop in feature.properties) {
if (prop == "id" ){
//do nothing
}
else if (prop == "website"){
popupcontent.push("<tr><td>" +prop + ": </td><td>" + "<a link href='" + feature.properties[prop] + "'></a></td></tr>");
}
else {
popupcontent.push("<tr><td>" +prop + ": </td><td>" + feature.properties[prop].replace(";", ", ") + "</td></tr>");
}
}
I believe there is something wrong with the statement in the if function, but I can't figure it out. Thanks for any help :)
I found the solution, just a few typos plus no text in the link:
var popupcontent = [];
for (var prop in feature.properties) {
if (prop == "#id" ){
//do nothing
}
else if (prop == "website"){
popupcontent.push("<tr><td>" +prop + ": </td><td>" + "<a link href='" + feature.properties[prop] + "'>" +feature.properties[prop] +"</a></td></tr>");
}
else {
popupcontent.push("<tr><td>" +prop + ": </td><td>" + feature.properties[prop].replace(";", ", ") + "</td></tr>");
}
}

how to append a dispatchEvent containing data to a class with jquery

I'm having problems with my script and i can't see the problem with it myself:
$("#mainsub").append(newRow + "<div class='showMore' onclick='document.dispatchEvent(expand, { 'postId': " + pf.id + " })'>Show More</div></div>");
My webkit debugger is saying: "Uncaught SyntaxError: Unexpected token ;" when i click on the element.
has anyone run into this before? is there a problem with the line of code?
EDIT:** newRow looks like this:
var newRow = "<div id=" + pf.id + ">"+rowContents;
rowContents is:
rowContents += "<div class='"+tagName+"'>"+tag.text()+"</div>";
tag name is just from some xml i am parsing.
Another edit: I'm just going to put the whole function in just in case this is helpful
pf.parseResults = function(){
$("#mainsub").empty();
var $xml = $(pf.xml);
var $query = $xml.find('query_result').children().each(function() {
var row = $(this);
var rowContents = "";
row.children().each(function() {
var tag = $(this);
var tagName = tag[0].tagName;
if(tagName != "ID"){
rowContents += "<div class='"+tagName+"'>"+tag.text()+"</div>";
}
if(tagName === "ID"){
pf.id = tag.text();
}
});
var newRow = "<div id=" + pf.id + ">" + rowContents;
$("#mainsub").append(newRow + "<div class='showMore' onclick='document.dispatchEvent(expand, { \'postId\': " + pf.id + " })'>Show More</div></div>");// this fires an event with data attached listing the id of the element the user tapped/**/
});
$("#mainsub").append("<div onclick='document.dispatchEvent(nextPage)'><p>Next</p></div>");// figure out how to not show next when there will not be another page
if(pf.getPage > 0){
$("#mainsub").append("<div onclick='document.dispatchEvent(previousPage)'><p>Previous</p></div>");// show go to previous as long at it will exist
}
};
When you nest quotes of the same type (single quotes in your case) you have to escape them like this:
$("#mainsub").append(newRow + "<div class='showMore' onclick='document.dispatchEvent(expand, { \'postId\': " + pf.id + " })'>Show More</div></div>");
As this line of code is quite long and I didn't wand to change too much, I'll point out that escaped quotes are in this expand, { \'postId\': " + pf.id + " } fragment.

Converting firefox javascript to IE javascript

I've been trying to get some AJAX code that runs fine in FireFox to run in IE.
I'm running into some trouble with updating some tables in the script though. I've seen numerous other people have similar issues, but none of the solutions they've found have worked for me. The problem occurs first on the line
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
Where I'm getting the error "'null' is null or not an object"
I'm pretty sure that all of my other errors are of the same type as this one, my AJAX script and some accompanying javascript is below.
<script type="text/javascript">
<!--
//obtains the box address for a QE3 on the system for the given index
function getQE3BoxAddressHash(index)
{
var retVal = 0x00000100; //initial value for QE3 boxes
retVal |= (index & 0x000000FF);
return retVal;
}
//obtains the box address for a QED on the system for the given index
function getQEDBoxAddressHash(index)
{
var retVal = 0x00001300; //initial value for QED boxes
retVal |= ((index & 0x0000000F) << 4);
retVal |= ((index & 0x000000F0) >> 4);
return retVal;
}
-->
</script>
<script type="text/javascript">
<!--
var textSocket;
function fillTables()
{
if(textSocket.readyState != 4)
return;
var qe3Table = document.getElementById("QE3_TABLE");
var qedTable = document.getElementById("QED_TABLE");
var rawData = textSocket.responseText.split("::::");
var qe3Data = new Array();
var qedData = new Array();
var qe3Index = 0;
var qedIndex = 0;
for(var item in rawData)
{
if(rawData[item].indexOf("QA") != -1)
{
qe3Data[qe3Index++] = rawData[item];
}
else if(rawData[item].indexOf("QED") != -1)
{
qedData[qedIndex++] = rawData[item];
}
}
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
qedTable.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
for(var value in qe3Data)
{
var components = qe3Data[value].split("-");
if(components.length != 3)
continue;
qe3Table.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQE3BoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
for(var value in qedData)
{
var components = qedData[value].split("-");
if(components.length != 3)
continue;
qedTable.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQEDBoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
}
function initAjax()
{
try
{
// Opera 8.0+, Firefox, Safari
textSocket = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
textSocket = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
textSocket = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("A browser error occurred.");
return false;
}
}
}
textSocket.onreadystatechange=fillTables
}
function reloadTables()
{
textSocket.open("GET","ajax_scripts/get_connected_boxes.php",true);
textSocket.send(null);
}
function init()
{
initAjax();
reloadTables();
}
window.onload=init();
-->
</script>
The problem is probably with:
var qe3Table = document.getElementById("QE3_TABLE");
If you're running this script before the body is loaded, that won't exist. Check to see if that variable has anything in it.
I Tried both of your guys' fixes but they didn't seem to help. In the end, I converted all calls of the form:
qe3TableNew.innerHTML = ("<tr>\n" +" <th>Name</th>\n" +" <th>Status</th>\n" +" <th>View Status</th>\n" +"</tr>\n");
to
var row;
var cell;
var text;
var font;
row = document.createElement("tr");
qe3TableNew.appendChild(row);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Name");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Status");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("View Status");
cell.appendChild(text);
This seemed to solve it, so I believe it has to do with IE's inability to handle changes to innerHTML.
Thanks for the help guys.
At least one issue (which could produce the above symptoms) is the line:
window.onload=init();
Hint: the () operator executes the function immediately and evaluates to the return value. This in turn may allow the XHR handler (in certain situations) to fire at a time when the DOM may not be ready.
Happy coding.

Categories

Resources