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.
Related
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).
I have written JavaScript outside the <body> end tag. Firebug is unable to detect the JavaScript and I am unable to detect the JavaScript error.
Here is my code:
</body>
<script type="text/javascript">
function displayIFrameContent()
{
var iFrame = document.getElementById("link");
var if1= "<iframe src='http://leadmarket.hol.es/forms/solar-power.php?adv_id=" + <?php echo($fetch_users_data['id']); ?>;
var if2= "<iframe src='http://leadmarket.hol.es/forms/kitchen-installation.php?adv_id=" + <?php echo($fetch_users_data['id']); ?>;
var if3= "<iframe src='http://leadmarket.hol.es/forms/conservatory.php?adv_id=" + <?php echo($fetch_users_data['id']);; ?>;
var host = document.getElementById("host");
var subId = document.getElementById("subid");
var errorClass = "box form-validation-error border-width-2";
if(host.value == "")
changeClass("host", errorClass);
if(host.value != "")
{
var iFrameEnd = " width='280' height='330' frameborder='0' scrolling='no'></iframe>";
var leadTypeSelect = document.getElementById("leadType");
var leadTypeValue = leadTypeSelect.options[leadTypeSelect.selectedIndex].value;
iFrame.value = "";
if(leadTypeValue == 1)
iFrame.value = if1 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
if(leadTypeValue == 2)
iFrame.value = if2 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
if(leadTypeValue == 3)
iFrame.value = if3 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
}
}
function changeClass(id, classname)
{
document.getElementById(id).setAttribute("class", classname);
}
</script>
</html>
Your help will be appreciated. Thanks in advance!
The code above contains PHP tags, which cause some syntax errors. In this case the Script panel just shows a message "No Javascript on this page". You should make sure they are interpreted by PHP before they are output to the browser.
Also JavaScript syntax errors are listed within the Console Panel. Make sure you have the option Show JavaScript Errors checked to see them.
Furthermore there's a detailed description about script debugging available within the Firebug wiki.
Sebastian
Hit a slight bump on something.
So I have a spreadsheet feed coming through via json.
Once they are loaded, if they contain a certain word, I want an elment that is already on the page to do something.
Having some trouble.
Here is my code:
/*feed*/
function displayContent(json) {
var len = json.feed.entry.length
var divtag = ''
for (var i=0; i<len; i++) {
divtag += [
'<div id=' +' tooltipwrap' + i + '>' +
'<span style="font-size:22px; font-weight:600;">',
json.feed.entry[i].gsx$studentname.$t + ' ' +
'<span class="hide" style="font-size:18px; font-weight:300;">',
json.feed.entry[i].gsx$classlevel.$t
+ '</span>' + '<span id=' + 'tooltipside' + i +'>' +
json.feed.entry[i].gsx$gender.$t + '-' +
'</span>',
'</div>'
].join('');
}
document.getElementById('tipswrap').innerHTML = divtag
}
/* what I wanted to do */
if ($('#tooltipside0').html() === "Senior") {
$("#test1").addClass('no');
}
Here is the JSFiddle
Pay attention to the tabulation. Right now your code is hard to read because you have failed to do so.
Here:
var len = json.feed.entry.length
var divtag = ''
you are missing semi-colons. You have to put semi-colon at the end of any operation, like this:
var len = json.feed.entry.length;
var divtag = '';
Semi-colons serve as operation separators.
Here:
divtag += [
'' +
'',
json.feed.entry[i].gsx$studentname.$t + ' ' +
'',
json.feed.entry[i].gsx$classlevel.$t
+ '' + '' +
json.feed.entry[i].gsx$gender.$t + '-' +
'',
'</div>'
].join('');
You have multiple problems:
You have failed to put your html attributes into quotes, so the resulting html will be invalid. Also, you have used comma instead of plus at the last concatenation.
CONCLUSION: You are obviously not ready to implement this code, because:
- You lack Javascript syntax knowledge
- You lack HTML syntax knowledge
- You do not pay attention to tabulation
As a consequence, your main problem is not what the question states, namely, how to add a class to an element depending on JSON feed. Your main problem is that you lack Javascript and HTML education. Please, follow some tutorials to be able to solve a problem and after that try again to solve your problem. If you fail to do so, then you will have at least an educated guess.
After adding the content to tipswrap add the condition
document.getElementById('tipswrap').innerHTML = divtag; //$('#tipswrap').html(divtag)
if ($.trim($('#tooltipside0').html()) === "Senior") {
$("#test1").addClass('no');
}
Demo: Fiddle
I recommend you add a class to all of your rows called student and then from there use this javascript:
function displayContent(json) {
var len = json.feed.entry.length
var divtag = ''
for (var i = 0; i < len; i++) {
divtag +=
'<div class="student" id="tooltipwrap'+i+'">'+
'<span style="font-size:22px; font-weight:600;">'+
json.feed.entry[i].gsx$studentname.$t +
'<span class="hide" style="font-size:18px; font-weight:300;">'+
json.feed.entry[i].gsx$classlevel.$t +
'</span> '+
'<span id="tooltipside'+i+'">'+
json.feed.entry[i].gsx$gender.$t + '-' +
'</span>'+
'</span>'+
'</div>';
}
document.getElementById('tipswrap').innerHTML = divtag
}
jQuery(document).ready(function($) {
$('.student').each(function() {
if ($(this).text().toLowerCase().indexOf("senior") >= 0)
$(this).addClass('senior');
});
});
Here's a demo
I am trying to add a hidden input field to a form when a span with class="checkbox" is clicked, and remove that same field when span with checkmark is clicked.
I am able to add the input, but I cannot remove it.
My HTML:
<span title="Here's My Title" class="wishlistcheck checkbox">1</span>
<form id="wishlistform"></form>
My Javascript:
$(document).ready(function() {
var appNum = 0;
$("span.wishlistcheck").click(function() {
var el = $(this);
var appName = el.attr("title");
var isChecked = el.hasClass('checkmark');
if(!isChecked) {
el.removeClass('checkbox');
el.addClass('checkmark');
appNum++
$("#wishlistform").append("<input id=\"" + appName + "\" type=\"hidden\" name=\"product_" + appNum + "\" value=\"" + appName + "\">");
} else {
el.removeClass('checkmark');
el.addClass('checkbox');
appNum--
$("input#" + appName).remove();
}
});
});
I guess you have to put the appNum-- after the .remove() method calling. Try it:
$(document).ready(function() {
var appNum = 0;
$("span.wishlistcheck").click(function() {
var el = $(this);
var appName = el.attr("title");
var isChecked = el.hasClass('checkmark');
if(!isChecked) {
el.removeClass('checkbox');
el.addClass('checkmark');
appNum++
$("#wishlistform").append("<input class=\"" + appName + "\" type=\"hidden\" name=\"product_" + appNum + "\" value=\"" + appName + "\">");
} else {
el.removeClass('checkmark');
el.addClass('checkbox');
appNum--
$("input[class=" + appName + "]").remove();
}
});
});
You probably have multiple DOM elements by that id tag, and so it may be removing an element matching that id but not the right one.
Try giving it a class name instead and getting more specific in your jQuery parameters by adding parent elements, i.e.
$('#wishlistform input#' + appName).remove();
function getList()
{
var string2 = "<img src='close.png' onclick='removeContent(3)'></img>" + "<h4>Survey Findings</h4>";
string2 = string2 + "<p>The 15 Largest lochs in Scotland by area area...</p>";
document.getElementById("box3text").innerHTML = string2;
var myList = document.getElementById("testList");
for(i=0;i<lochName.length;i++)
{
if(i<3)
{
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
else
{
var listElement = "Loch "+lochName[i];
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
}
}
This function generates a list with the 1st 3 elements being hyperlinks. When clicked they should call a function call getLoch(i) with i being the position of the item in the list. However when i pass it the value it just give it a value of 15, the full size of the array and not the position.
function getLoch(Val)
{
var str = "<img src='close.png' onclick='removeContent(4)'></img>" + "<h4>Loch " + lochName[Val] +"</h4>";
str = str + "<ul><li>Area:" + " " + area[Val] + " square miles</li>";
str = str + "<li>Max Depth:" + " " + maxDepth[Val] + " metres deep</li>";
str = str + "<li>County:" + " " + county[Val] + "</li></ul>";
document.getElementById("box4").innerHTML = str;
}
There are 2 errors in your code as far as I can see. The first is the way you create your link.
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
This will actually result in code like this:
<a href='javascript:getLoch(i)'>Loch name</a>
Passing a variable i is probably not what you intended, you want it to pass the value of i at the time your creating this link. This will do so:
var listElement = "<a href='javascript:getLoch(" + i + ")'>" + "Loch "+ lochName[i] + "</a>";
So why does your function get called with a value of 15, the length of your list? In your getList function, you accidently made the loop variable i a global. It's just missing a var in your loop head.
for(var i=0;i<lochName.length;i++)
After the loop finished, i has the value of the last iteration, which is your array's length minus 1. By making i a global, and having your javascript code in the links use i as parameter, getLoch got called with your array length all the time.