How to validate HTML content with multiple variables put inside a string - javascript

I've below code
issuesList.innerHTML += "<div class=\"well\">" +
"<h6> Issue Id:" + id + "</h6" +
"<p><span class=\"label label-info\">" + status + "</span></p>" +
"<h3>" + desc + "</h3>" +
"<p><span class=\"glyphicon glyphicon-time\">" + severity + "</span></p>" +
"<p><span class=\"glyphicon glyphicon-user\">" + assignedTo + "</span></p>" +
"Close" +
"<a href=\"#\ onclick=\"deleteIssue( \"" + id + "\")\" class=\"btn btn-danger\>Delete</a>" +
"</div>";
I wish to validate if this is correct format of HTML as it contains many variable and it's hard to debug if something goes wrong.

To make it one degree less complicated, you can use single quotes to wrap class or style declarations and double quotes to wrap the overall html (or vice versa).
In this piece of html, I observed issued at closing of </h6> and in the class declaration of last anchor tag.
issuesList.innerHTML += "<div class='well'>" +
"<h6> Issue Id:" + id + "</h6>" +
"<p><span class='label label-info'>" + status + "</span></p>" +
"<h3>" + desc + "</h3>" +
"<p><span class='glyphicon glyphicon-time'>" + severity + "</span></p>" +
"<p><span class='glyphicon glyphicon-user'>" + assignedTo + "</span></p>" +
"<a href='#' onclick= 'setStatusClosed(\"" + id + "\")' class='btn btn-warning'>Close</a>" +
"<a href='#' onclick='deleteIssue( \"" + id + "\")' class='btn btn-danger'>Delete</a>" +
"</div>";
You may use following function to validate the html so created:
function validator(createdhtml) {
var tempdiv = document.createElement('div');
tempdiv.innerHTML = createdhtml;
return tempdiv.innerHTML;
}
Further I recommend reading:
check-if-html-snippet-is-valid

Related

Trouble with jQuery loop through array of objects

I'm trying to nest 3 divs within a "row" div.
I had this working in "long format" (multiple var's instead of looping through the array). I've refactored my code and now I don't get any error codes AND my code does not append to the HTML file. When I console log I get an array with 3 objects. I'm sure i'm missing something minor.
Anyways some help would be great!
<div class="row">
**nested divs go here.
</div>
$(document).ready(function() {
$.get("http://api.openweathermap.org/data/2.5/forecast/daily?id4726206&cnt=3", {
APPID: "MY API KEY",
lat: 29.423017,
lon: -98.48527,
units: "imperial"
}).done(function(data) {
var stationId = data.city.name;
// Stattion Name
$('#station').append(stationId);
//console.log(data);
var forecast = data.list;
//Wind Direction in Compass Format
function getDirection(dir) {
var compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
var result = Math.floor((360 - dir) / 22.5);
return compass[result];
}
//Forecast Variables
$.each(forecast, function(i, v) {
var html = '';
html += "<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>";
html += "<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°';
html += " / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>";
html += "<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon;
html += ".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main;
html += "</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>";
html += "<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>";
html += "<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed));
html += " mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>";
html += "<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div>";
return html;
});
$('.forecast').append(forecast);
console.log(forecast);
});
});
You are trying to append the array forecast in html. which wont work. You should declare the html variable outside and then use it in append function.
I will also recommend to use string builder logic using array and then convert it to string and append it. remember string concatenation is heavy operator as it creates new instance of elememt every time concatenation is done :
var html = [];
$.each(forecast, function(i, v) {
html.push("<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>");
html.push("<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°');
html.push(" / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>");
html.push("<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon);
html.push(".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main);
html.push("</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>");
html.push("<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>");
html.push("<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed)));
html.push(" mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>");
html.push("<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div></div>");
});
$('.forecast').append(html.join(""));

concat ' in JS Code (Jquery)

Hi together I've got a problem with the ' and " in my js code.
$(".searchResultsMember table").append("<tr>" +
"<td>" +
"<a href='#' title='Statistik' data-container='body'
data-toggle='tooltip' data-placement='bottom' onclick='open_statistic('/memberships/statistik/', '"+
data.results[i].firstname +" "+
data.results[i].lastname +"','"+ data.results[i].id +
"');return false; '><img src='/images/iconpack/table.png' alt='Statistic'/></a> "+
[....]
The Problem is in the onclick part .. can someone help me with this ?
In JavaScript, you can mix and match ' and " as long as you use them in pairs, eg:
var x = "a";
var y = 'b';
You can also combine these on the same line, eg:
var z = "a" + 'b';
so you pick the one you need depending on the content (unless you have some nefarious coding standards written by someone that doesn't understand this (which I've seen..))
to concat a single quote, surround in doubles and the other way, eg:
var x = "'" + '"'; x == '"
this also applies to attributes:
<a href="#" title='double quote (")'>
<a href="#" title="single quote (')">
so you can fix your code by changing the quotes:
$(".searchResultsMember table").append(
"<tr>"
+ "<td>"
+ "<a href='#' title='Statistik'"
+ " data-container='body' data-toggle='tooltip' data-placement='bottom'"
+ ' onclick="open_statistic('
+ "'/memberships/statistik/', '"
+ data.results[i].firstname
+ " "
+ data.results[i].lastname
+ "','"
+ data.results[i].id
+ "');return false; "
+ '">'
+ "<img src='/images/iconpack/table.png' alt='Statistic'/></a> "+
[....]
But, having done this for you above - it's really confusing! (and therefore prone to errors)
So break it up into steps with variables, and break out just the double quotes, eg:
var onclick = "open_statistic('/memberships/statistik/', '" + ... + "');return false;";
$(".searchResultsMember table").append(
"<tr>"
+ "<td>"
+ "<a href='#' title='Statistik'"
+ " data-container='body' data-toggle='tooltip' data-placement='bottom'"
+ " onclick=" + '"' + onclick + '"' + ">"
....

jquery $.each not giving all the information in the table

Fiddle
I want to put the names of all record in my array into a table my array isn't index correctly so i used $.each instead of iterating over the using for loop. My problem is I only get to show the last element but if i try to show a value that is existing to both the array it is showing correctly.
What am i missing in this code.
Any idea is appreciated
This is my javascript
for (var i = 0; i < name.length; i++) {
var names = name[i].Names;
$.each(names, function (item, names) {
tr = $('<tr class=""/>');
//console.log(complainant[obj]);
//var names = complainant[obj];
//if(names.hasOwnProperty('fname')){
console.log(names.suffix);
var acronymc;
var upper = names.mname.toUpperCase();
if (upper) {
var matches = upper.match(/\b(\w)/g);
//var matches = upper.replace(/^(\S+)\s+(\S).*/, '$1 $2.');
//acronym = upper.slice(0,1);
var acronym1 = matches.join('');
acronymc = acronym1.slice(-1);
} else {
acronymc = '';
}
tr.append("<td id=''>" + "<span id='fname'>" + names.fname + "</span>" + " " + "<span id='mname'>" + acronymc + "</span>" + " " + "<span id='lname'>" + names.lname + "</span>" + " " + "<span id='suffix'>" + names.suffix + "</span>" + "</td>");
tr.append("<td id=''>" + '<span id="street">' + names.street + '</span>' + " " + '<span id="brgy">' + names.brgy + '</span>' + " " + '<span id="town">' + names.town + '</span>' + " " + '<span id="city">' + names.city + '</span>' + "</td>");
tr.append("<td id=''>" + names.contactnum + "</td>");
tr.append("<td id=''>" + "<a href='#' class='editcomplainant'>Edit</a>" + "/" + "<a href='#' class='delete'>Delete</a>" + "</td>");
//}
});
$("#nameslist").append(tr);
}
Put the $('#nameslist').append(tr); call inside the $.each block.
Here is a way of improving the creation of tds:
var html =
"<td>" +
"<span id='fname'/> " +
"<span id='mname'/> " +
"<span id='lname'/> " +
"<span id='suffix'/>" +
"</td>";
var td = $(html);
td.find('#fname').text(names.fname);
td.find('#mname').text(acronymc);
td.find('#lname').text(names.lname);
td.find('#suffix').text(names.suffix);
tr.apppend(td);
Why is this better (imho)?
You will not create unintentional html tags by having < and > inside the variables.
Appropriate escaping (auml codes) will be automatically generated
It is easier to read

Adding "Edit" button with jQuery .append

I am building an application that would allow adding tasks to the list,
and I want to add an edit button, that would allow user to edit each item from the list and then save or delete the amended item. Basically I want my .append code to attach an "Edit" button to each row.
Here is my current .append code
var id_counter = 0;
if ( valid ) {function increment(){id_counter++;} increment();
var $task = $("<div class='taskList' id='"+ id_counter +"'><ul class='taskScreen2'><tr>"
+ "<td><h1>" + type.val() + "</h1></td>"
+ "<td class='title'><h3>" + title.val() + "</h3></td>"
+ "<td>" + wordcount.val() + "</td>"
+ "<td><p>" + description.val() + "</p></td>"
+ "<td>" + deadline.val() + "</td>"
+"<td><button onclick='edit("+id_counter+")'>"+"edit"+"</button></td>"
+ "</tr></ul></div>"
).appendTo("#tasks2 tbody");
I don't know if I understood the question properly, but I think this should do what you like.
if ( valid ) {
var $task = $("<tr class='taskList'>"
+ "<td><h1>" + type.val() + "</h1></td>"
+ "<td class='title'><h3>" + title.val() + "</h3></td>"
+ "<td>" + wordcount.val() + "</td>"
+ "<td><p>" + description.val() + "</p></td>"
+ "<td>" + deadline.val() + "</td>"
//new button
+ "<td><button onclick='edit()'>"+ "Edit" + "</button></td>"
+ "</tr>"
).appendTo("#tasks2 tbody");
if you want to act differently depending on the row, you could call the edit function with a parameter. e.g edit(row_id)
EDIT
var id_counter
var $task = $("<tr class='taskList' id='"+ id_counter +"'>"
for the addition of the id in the code and
+"<td><button onclick='edit("+id_counter+")'>"+"edit"+"</button></td>"
for the button code
you could start with id_counter = 0; and then add plus one each time

Bootstrap 3.2.0: Open dropdown menu with javascript

I'm having difficulty opening a dropdown menu with bootstrap 3.2.0 and javascript. Here is the html (added dynamically with javascript to dom):
<ul id="assigned" class="nav navbar-nav">
<li id="shopping-cart-dropdown" class="dropdown">
<a href="#" id="dropdown-toggle" class="dropdown-toggle button-assigned" data-toggle="dropdown">
<span class="span-assigned">(0/5)</span>
<span class="caret"></span>
</a>
<ul class="dropdown-menu assigned-menu" role="menu">
<p class="assigned-info">
<span class="bold">You have 5 assignments available.</span>
</p>
</ul>
</li>
</ul>
And Javascripts I've tried so far:
$("#shopping-cart-dropdown").addClass("open"); //open class not added in dom. bootstrap prevents this?
$("#dropdown-toggle").dropdown("toggle"); //nothing happens
$("#dropdown-toggle").click(); //no luck either
$(".assigned-menu").css("display", "block"); //this displays the dropdown but its not closable forever
var dd = $('#shopping-cart-dropdown');
dd.closable = true; //I can't make it closable with this code
Edit: When I first fire the toggle after I create the dropdown contents with
$("#dropdown-toggle").dropdown("toggle");
It works
But when I call the same function again it doesnt. Here is the function that refreshes dropdown contents (as well as first time creating them):
for (var cnt = 0; cnt < this.AssignedRooms.length; cnt++) {
var litext = "";
litext += "<div class='assigned-item' id='assigned-room" + this.AssignedRooms[cnt].RoomNo + "' " + "building-no='" + this.AssignedRooms[cnt].BuildingNo + "'" + " floor-no='" + this.AssignedRooms[cnt].FloorNo + "' room-no='" + this.AssignedRooms[cnt].RoomNo + "'>";
litext += (this.EnableCampus ? "<span class='small bold'>Building </span><span class='small'>" + this.AssignedRooms[cnt].BuildingNo + ", </span>" : "");
litext += "<span class='small bold'>Floor </span><span class='small'>" + this.AssignedRooms[cnt].FloorNo + "</span>, ";
litext += "<span class='small bold'>Room </span><span class='small'>" + this.AssignedRooms[cnt].RoomNo + "</span>";
litext += "</div>";
litext += "<div class='assigned-cancel' id='assigned-room-cancel" + this.AssignedRooms[cnt].RoomNo + "' " + "building-no='" + this.AssignedRooms[cnt].BuildingNo + "'" + " floor-no='" + this.AssignedRooms[cnt].FloorNo + "' room-no='" + this.AssignedRooms[cnt].RoomNo + "'>";
litext += "<img src='../../PickContent/img/cancel-small.png' title='Cancel Room " + this.AssignedRooms[cnt].RoomNo + "'/>";
litext += "</div>";
html += "<li class='assigned-list-item'>" + litext + "</li>";
}
$("#assigned ul.dropdown-menu").html(html);
if (full) {
$("#dropdown-toggle").dropdown("toggle");
}
You are using bootstrap 3.2. You don't need extra JavaScript to make the drop down work.
If it is not working with pure Bootstrap. Make sure you have Jquery included as well as Bootstrap. Jquery is REQUIRED for the drop down to work.
<script type="text/javascript" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
I suppose your refresh function is inside a link/button click event handler.
Try adding return false; at the end of the function to prevents the browser from performing the default action for that link/button.
$("#button").click(function () {
...
for (var cnt = 0; cnt < this.AssignedRooms.length; cnt++) {
var litext = "";
litext += "<div class='assigned-item' id='assigned-room" + this.AssignedRooms[cnt].RoomNo + "' " + "building-no='" + this.AssignedRooms[cnt].BuildingNo + "'" + " floor-no='" + this.AssignedRooms[cnt].FloorNo + "' room-no='" + this.AssignedRooms[cnt].RoomNo + "'>";
litext += (this.EnableCampus ? "<span class='small bold'>Building </span><span class='small'>" + this.AssignedRooms[cnt].BuildingNo + ", </span>" : "");
litext += "<span class='small bold'>Floor </span><span class='small'>" + this.AssignedRooms[cnt].FloorNo + "</span>, ";
litext += "<span class='small bold'>Room </span><span class='small'>" + this.AssignedRooms[cnt].RoomNo + "</span>";
litext += "</div>";
litext += "<div class='assigned-cancel' id='assigned-room-cancel" + this.AssignedRooms[cnt].RoomNo + "' " + "building-no='" + this.AssignedRooms[cnt].BuildingNo + "'" + " floor-no='" + this.AssignedRooms[cnt].FloorNo + "' room-no='" + this.AssignedRooms[cnt].RoomNo + "'>";
litext += "<img src='../../PickContent/img/cancel-small.png' title='Cancel Room " + this.AssignedRooms[cnt].RoomNo + "'/>";
litext += "</div>";
html += "<li class='assigned-list-item'>" + litext + "</li>";
}
$("#assigned ul.dropdown-menu").html(html);
if (full) {
$("#dropdown-toggle").dropdown("toggle");
}
...
return false; //Add this line
});

Categories

Resources