How do I write into the html using JavaScript? - javascript

<script>
for(var numCols = 1; numCols <= 12; numCols++){
document.write(
"<div class='row'>" +
"<div class='well text-center col-lg-" + [numCols] + "'>" + ".col-lg-" + [numCols] + "</div>" +
"</div>";
);
}
</script>
I know there's document.write/document.writeln but I have this script and I don't know what's wrong. I'm trying to visualize Bootstrap's col-md-* thing

Remove the semicolon after last </div>
<script>
for(var numCols = 1; numCols <= 12; numCols++){
document.write(
"<div class='row'>" +
"<div class='well text-center col-lg-" + [numCols] + "'>" + ".col-lg-" + [numCols] + "</div>" +
"</div>"
);
}
</script>

The problem is with the [numCols] part of string concatenation and unnecessary semicolon at the end of function call argument.
Basically, what this "part" does is it returns an Array with one element, resolving to numCols variable value. You want to return the variable itself, so just remove [] wrapper. Technically, JS allows you to use this syntax, because it casts the array to string, concatenating all the elements within the array with an empty string (equivalent to [ numCols ].join("")), but it's just unnecessary in this case.
Another thing - you are terminating HTML string with "</div>"; - the semicolon is invalid in this place, you should remove it.

Remove the semiColon inside your document.write method.
for(var numCols = 1; numCols <= 12; numCols++){
document.write(
"<div class='row'>" +
"<div class='well text-center col-lg-" + [numCols] + "'>" + ".col-lg-" + [numCols] + "</div>" +
"</div>"
);
}

Be aware. Working with the DOM means, the client has to do the work. Doing several changes to the DOM could lead us to several performance issues.
The ideal is, do not modify the DOM. If you really need to do this. Find the way to do the less changes to the DOM.
The piece of code you provide us have the possibility to be improved.
In your code, you are using a loop. 12 times the DOM would change. These is far away of be a good practice.
A better approach is to write the DOM only 1 time. In this scenario you can easily achieve adding two lines of code.
From this (12 DOM changes):
for(var numCols = 1; numCols <= 12; numCols++){
document.write(
"<div class='row'>" +
"<div class='well text-center col-lg-" + [numCols] + "'>" + ".col-lg-" + [numCols] + "</div>" +
"</div>"
);
}
To this (1 change to the DOM):
var newHtml = '';
for(var numCols = 1; numCols <= 12; numCols++){
newHtml+= "<div class='row'>" +
"<div class='well text-center col-lg-" + [numCols] + "'>" + ".col-lg-" + [numCols] + "</div>" +
"</div>";
}
document.write(newHtml);

You can use innerHTML to change the content of DOM element when the page is loaded.
window.onload = function() {
var content = "";
for(var numCols = 1; numCols <= 12; numCols++) {
content += "<div class='row'>" +
"<div class='well text-center col-lg-" + numCols + "'>" + ".col-lg-" + numCols + "</div>" +
"</div>";
}
document.getElementsByTagName('body')[0].innerHTML = content;
}

Related

Jquery, create table tag with custom ID, then later refer to that ID and append new tags to it

So essentially I want to append a < table> tag to < body> with a custom ID and then later in my code refer to the table with the custom ID and append < tr>, < td>, or < th> to it.
Here's an example:
dataHold = data[1].split("#")[1]; //just imagine this as "yahoo.com"
if( !hold.includes( dataHold ) )
{
$("body").append
(
"<table id='"+dataHold+"'>"+
"<tr>"+
"<th>"+dataHold+"</th>"+
"</tr>"+
"</table>"
);
$( "#"+dataHold ).append
(
"<tr>"+
"<td>"+data[1]+"</td>"+
"<td>"+data[2]+"</td>"+
"<td>"+data[3]+"</td>"+
"</tr>"
);
}
It does append the < table> tag, but for some reason the < tr> tag appending doesn't work and I can't figure out why. Any ideas?
Your jQuery code is fine, so the problem is with your variables or lack of inclusion of jQuery. Ensure that you have jQuery loaded, and that your three variables (hold, data and dataHold) actually resolve. Don't forget that hold is not supposed to include dataHold for the if condition to be entered.
The following snippet shows this working as expected (with all variables set correctly):
const hold = data = [2, 3, 4, 5];
const dataHold = 1;
if (!hold.includes(dataHold)) {
$("body").append(
"<table id='" + dataHold + "'>" +
"<tr>" +
"<th>" + dataHold + "</th>" +
"</tr>" +
"</table>"
);
$("#" + dataHold).append(
"<tr>" +
"<td>" + data[1] + "</td>" +
"<td>" + data[2] + "</td>" +
"<td>" + data[3] + "</td>" +
"</tr>"
);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your code works just fine when isolated to this snippet:
var dataHold = "testId";
var data = ["foo", "bar", "carrots", "broccoli"];
$("body").append(
"<table id='" + dataHold + "'>" +
"<tr>" +
"<th>" + dataHold + "</th>" +
"</tr>" +
"</table>"
);
$("#" + dataHold).append(
"<tr>" +
"<td>" + data[1] + "</td>" +
"<td>" + data[2] + "</td>" +
"<td>" + data[3] + "</td>" +
"</tr>"
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Ensure that you have correctly included the jQuery library before using the jQuery selector function ('$'). Also, use the built-in debugger in your favorite browser to ensure that the values of dataHold and data are exactly what you expect them to be. If they are null or undefined you may get errors in the string concatenation resulting in your row not being appended.

How to append each object to its respective 'block' of elements?

var clubbingLocations = $('#clubbing-locations');
$.getJSON("/js/location.json", function(data) { //load json
for (var i = 1; i <= data.locations.length; i++){ //loop through json, append html and objects
clubbingLocations.append("<div class='night-type location'>" +
"<a href='location.html'>" +
"<div class='overlay'>" +
"<div class='overlay'>" +
"<span class='fav checked glyphicon glyphicon-heart' aria-hidden='true'></span>" +
"<h4>" + data.locations[i].name + "</h4>" +
"<div class='rating-hold'>" +
"</div>" +
"</div>" +
"</a>" +
"</div>"
);
for (var j = 1; j <= data.locations[i].rating; j++){
$('.rating-hold').append("<span class='filled glyphicon glyphicon-star' aria-hidden='true'></span>");
}
}
I am trying to append the object's review to each of its respective rating-hold, however, the reviews are accumulating and adding themselves on to each other instead of appending to the respective class, them moving on.
The first rating inserts its self perfectly, but after that they start adding themselves onto each other.
Create a jQuery object with your html string first.
Then you can search within that object to find the current rating-hold and append icons to it.
Finally, append the whole object including the icons to clubbingLocations
for (var i = 0; i <= data.locations.length - 1; i++){ //loop through json, append html and objects
// create jQuery object
var $nightType= $("<div class='night-type location'>" +
"<a href='location.html'>" +
"<div class='overlay'>" +
"<div class='overlay'>" +
"<span class='fav checked glyphicon glyphicon-heart' aria-hidden='true'></span>" +
"<h4>" + data.locations[i].name + "</h4>" +
"<div class='rating-hold'>" +
"</div>" +
"</div>" +
"</a>" +
"</div>"
);
for (var j = 0; j <= data.locations[i].rating; j++){
// append icons to object created above
$nightType.find('.rating-hold').append("<span class='filled glyphicon glyphicon-star' aria-hidden='true'></span>");
}
// append object to dom
clubbingLocations.append($nightType);
}
You can use JQuery .each documentation
$('.rating-hold').each(function(index){
$(this).append('html code here');
})
Your are appending using the .rating-hold alone, which will append all to the first location, try giving locations ids, and assign stars to each separately using this instead:
var clubbingLocations = $('#clubbing-locations');
$.getJSON("/js/location.json", function(data) { //load json
for (var i = 0; i <= data.locations.length - 1; i++){ //loop through json, append html and objects
clubbingLocations.append(
"<div id='location" + i + "' class='night-type location'>" +
"<a href='location.html'>" +
"<div class='overlay'>" +
"<div class='overlay'>" +
"<span class='fav checked glyphicon glyphicon-heart' aria-hidden='true'></span>" +
"<h4>" + data.locations[i].name + "</h4>" +
"<div class='rating-hold'>" +
"</div>" +
"</div>" +
"</a>" +
"</div>"
);
for (var j = 0; j <= data.locations[i].rating; j++){
$('#location' + i + ' .rating-hold').append("<span class='filled glyphicon glyphicon-star' aria-hidden='true'></span>");
}
}

Display a grid from a clicked link using typescript

I'm trying to write code that will display a grid when a link is clicked, and I managed to get the link display, but failing to get grid displayed at the bottom of the page. Thanks for your help.
*
export function setCustomLinkContent(divId: string, field: propertybox.Field) {
var container = $('#' + divId);
container.height(70);
container.width(260);
container.append("<p><a target='_blank' href=\"http://localhost\">View all works</a></p>");
this.container.prepareGridContainer();
var gridContainer = $("#" + this.container);
var gridContHeight = gridContainer.height() - 27 - 43;
var workHtml =
"<div id='" + this.workContainer + "-heading' class='orm-table-title'>" +
"<label>" + this.headerLabel + "</label>" +
"</div>" +
"<div id='" + this.workContainer + "-table' class='map-work-grid' style='height: " + gridContHeight + "px'>" +
"<table style='margin: 0 auto; width: 100%; overflow-x: auto'>" +
"<thead>" +
"<tr id='" + this.tableHeader + "'></tr>" +
"</thead>" +
"<tbody id='" + this.tableBody + "'></tbody>" +
"</table>" +
"</div>";
gridContainer.append(workHtml);
}
*
Very likely you have the wrong this. Since your function is not a part of a class this doesn't seem to make sense here.
More about this: https://www.youtube.com/watch?v=tvocUcbCupA&hd=1

Unknown error when calling Array.length

first of all i need to say that i don't have much experience with JS. currently i'm trying to implement an web application with MVC framework. I'm in a work to develop an app that is also compatible with Internet explorer. in that case i'm using following JS method to populate a table which is working fine with all the browsers....
function populateTable(array) {
document.getElementById("instalationTable").style.display = "block";
var table = document.getElementById("ActivityDescription_installationID");
table.innerHTML = "";
elementsInTable = array;
var x = 0;
for (i = 0; i < (array.length * 2) ; i++) {
//alert(i);
if ((i % 2) == 0) {
//ID Row
var row = table.insertRow(i);
var cell_1 = row.insertCell(0);
cell_1.innerHTML = "<input type='text' disable='' class='form-control' value=" + array[x] + ">";
x = x + 1;
var cell_2 = row.insertCell(1);
cell_2.innerHTML = "<span class='btn btn-default' onclick='showEditRow(this)'><img src='../../Content/images/1414409386_48-24.png' /></span>";
var cell_3 = row.insertCell(2);
cell_3.innerHTML = "<span class='btn btn-default' onclick='removeRow(this)'>X</apan>";
}
else {
//Detail Row
var rowDetails = table.insertRow(i);
var cell = rowDetails.insertCell(0);
//cell.colspan = "3";
cell.innerHTML = "<table style='background-color:rgb(98, 98, 98);color:black;border- radius: 5px;' margin:2%; >" +
"<tr>" +
"<td><input type='checkbox' id='"+x+"_appServer'/> Application Server</span></td>" +
"<td>" +
"<select id='" + x + "_appServerVersion'>" +
"<option>Application version</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='2'><input type='radio' name='database' id='"+x+"_emptyDb' onChange='enableOptions(1)'/>" +
" Empty Database</br><input type='radio' name='database' id='" + x + "_instalationSlt' onChange='enableOptions(2)'/> Something Databse</td>" +
"</tr>" +
"<tr id='emptyDB'>" +
"<td>" +
"Oracle Version"+
"<select id='JS_OraVersion' name='" + x + "_oraVersion' style='width:100%'>" +
"<option>Ora version</option>" +
"</select>" +
"</td>" +
"<td>" +
"Character Set" +
"<select id='JS_ChaSet' name='" + x + "_ChaSet' style='width:100%'>" +
"<option>Cha Set</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr id='dbImport'>" +
"<td>" +
"Something version" +
"<select id='JS_ImportVersion' name='" + x + "_ImportVersion' style='width:100%'>" +
"<option>Something version</option>" +
"</select>" +
"</td>" +
"<td>" +
"Something Charachter" +
"<select id='JS_ImportChaSet' name='" + x + "_ImportChaSet' style='width:100%'>" +
"<option>Something Cha</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='2'>" +
"Additional Requests </br>" +
"<textarea rows='4' id='" + x + "_specialReq' cols='37'> </textarea>" +
"<td/>"+
"</tr>"+
"</table>";
rowDetails.style.display = 'none';
Lock();
}
}
document.getElementById("instalationTable").style.display = "block";
}
i'm populating a form on the above table row, that collects some data to continue. to collect data i'm using following function which works fine with Google chrome but not with Internet explorer..
function getAllData() {
var StringtoSent = "";
for (i = 0; i < (elementsInTable.length) ; i++) {
var InsId = elementsInTable[i];
var _appServer = document.getElementById((i + 1) + "_appServer").checked;
var _appServerVersionDropDown = document.getElementById((i + 1) + "_appServerVersion");
var _appServerVersion = _appServerVersionDropDown.options[_appServerVersionDropDown.selectedIndex].value;
var _emptyDb = document.getElementById((i + 1) + "_emptyDb").checked;
var _instalationSlt = document.getElementById((i + 1) + "_instalationSlt").checked;
var _oraVersionDropDown = document.getElementsByName((i + 1) + "_oraVersion")[0];
var _oraVersion = _oraVersionDropDown.options[_oraVersionDropDown.selectedIndex].value;
var _ChaSetDropDown = document.getElementsByName((i + 1) + "_ChaSet")[0];
var _ChaSet = _ChaSetDropDown.options[_ChaSetDropDown.selectedIndex].value;
var _ImportVersionDropDown = document.getElementsByName((i + 1) + "_ImportVersion")[0];
var _ImportVersion = _ImportVersionDropDown.options[_ImportVersionDropDown.selectedIndex].value;
var _ImportChaSetDropDown = document.getElementsByName((i + 1) + "_ImportChaSet")[0];
var _ImportChaSet = _ImportChaSetDropDown.options[_ImportChaSetDropDown.selectedIndex].value;
var _specialReq = document.getElementById((i + 1) + "_specialReq").value;
StringtoSent = StringtoSent + "," + InsId + "," + _appServer + "," + _appServerVersion + "," + _emptyDb + "," + _instalationSlt + "," + _oraVersion + "," + _ChaSet + "," + _ImportVersion + "," + _ImportChaSet + "," + _specialReq + "|";
//return StringtoSent;
document.getElementById("ActivityDescription_instalationDetails").value = StringtoSent;
}
}
following image shows the error that im getting when it is ruining on VS 2012s IIS Express.
for (i = 0; i < (elementsInTable.length) ; i++) {
is the place that indicates as the error place . it always highlight the "elementsInTable.length" code segment.
Actually this error message elaborate nothing. i found some articles about the same error but occurring when trying to change the inner HTML of an element. but those solutions are not compatible for this situation.. Please help me with the problem
thanks in advance
Finally i found the Error
cell.innerHTML = "<table style='background-color:rgb(98, 98, 98);color:black;border- radius: 5px;' margin:2%; >" +
in above line i mistakenly added a CSS attribute "margin:2%;" in to a wrong place. Google chrome is intelligence enough to manage the situation and proceed the activity but Internet Explorer is not. as i found, this is the fact that prompt same error in different situations.
EG:
http://www.webdeveloper.com/forum/showthread.php?22946-innerHTML-amp-IE-Unknown-Runtime-Error
http://www.webdeveloper.com/forum/showthread.php?22946-innerHTML-amp-IE-Unknown-Runtime-Error
So if you got any unknown error in your Java Script code which uses "element.InnerHTML" or "document.Write" its better to check whether your tags are properly closed.
and i found several other situations that is generating same error
IE shows run time error for innerHTML
InnerHTML issue in IE8 and below
most of the times you can avoid this error by following W3C tag recommendations (http://www.w3.org/TR/html401/struct/global.html).

How to add new class to the existing class in this case

I am new to Javascript and Jquery so please excuse if this is a dumb question
HTML is being constructed dynamically as shown
var favoriteresultag = '<ul>';
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
How can i add/concat one more variable to the class ulseWrap lielement ??
I tried this way
var classactive = '';
if (some condition) {
classactive = 'activeRest';
} else {
classactive = '';
}
favoriteresultag += "<section id='" + name + "' class='ulseWrap lielement '+classactive+' '>" + "<div class='intit someclassss'>" + name + "</div>" + "</section>";
String concatenation, just like you're doing:
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement " + classactive + "'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
Try this with jquery if you are using it
$('.actual_class').addClass('new_class')
In your case can be
$('#'+name).addClass('activeRest')
or
$('.ulseWrap.lielement').addClass('activeRest')

Categories

Resources