Jquery: append to div with a class that has a variable name - javascript

So I'm working on a quick app that when you press a button, dog pictures show up. I want the pictures to appear in rows. So I started to create divs with the class 'dog row' and ended the name with a variable.
While the creation of that div is successful. I can't seem to append anything to the div itself.
for (i=0; i<dogPool.length; i++){
if (i%5 == 0){
$('.dogTable').append(
"<div class='dogLine dogRow" + rowNumber + "'></div>"
);
console.log("<div class='dogLine dogRow" + rowNumber + "'></div>");
rowName = "'.dogRow" + rowNumber + "'";
rowNumber++;
}
console.log("row: " + rowName);
$(rowName).append(
"<p>"+ i + "</p>"
);
}

The problem is here rowName = "'.dogRow" + rowNumber + "'";
You should fix like this
var rowName = '.dogRow' + rowNumber;
var dogPool = ["dog1", "dog2"];
var rowNumber = 0;
for (i=0; i<dogPool.length; i++){
$('.dogTable').append(
"<div class='dogLine dogRow" + rowNumber + "'></div>"
);
console.log("<div class='dogLine dogRow" + rowNumber + "'></div>");
var rowName = '.dogRow' + rowNumber;
rowNumber++;
$(rowName).append(
"<p>"+ i + "</p>"
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dogTable">
123
</div>

Related

internal html script window.addEventListener / window.onload not working to edit specific div

I want to add a table to the div contents according to user input, somehow the table does not show even though the prompts starts. html as below:
<div id= "content">
<h3>Customise your table</h3><br/>
</div>
<script>
function createTable(){
var tablerow, tablecol, tableheight, tablewidth, tableborder, borderstyle;
tablerow = prompt("Please enter your desired number of table rows(0-unlimited whole
numbers):");
tablecol = prompt("Please enter your desired number of table columns(0-unlimited whole
numbers):");
tableheight = prompt("Please enter your desired table height (non-negative):");
tablewidth = prompt("Please enter your desired table width (non-negative):");
tableborder = prompt("Please enter your desired border size(non-negative):");
borderstyle = prompt("Please enter your desired border style and color (only html border
styles/color accepted):");
document.getElementsById("content").innerHTML += "<table style='border: " + tableborder + "px " + borderstyle + "'"
+ "' height= '" + tableheight + "px' width= '" + tablewidth + "px'>";
for (var row = 0; row < tablerow; row++){
document.getElementsById("content").innerHTML += "<tr style='border: " + tableborder + "px " + borderstyle + "'>";
if (row == 0){
for (var col = 0; col < tablecol; col++){
document.getElementsById("content").innerHTML += "<th style='border: " + tableborder + "px " + borderstyle + "'>Column</th>";
}
document.getElementsById("content").innerHTML += "</tr>";
}
else {
for (var col = 0; col < tablecol; col++){
var tableElement = (tablecol * (row-1)) + 1 + col;
document.getElementsById("content").innerHTML += "<td style='border: " + tableborder + "px " + borderstyle + "'>" + tableElement + "</td>";
}
document.getElementsById("content").innerHTML += "</tr>";
}
}
document.getElementsById("content").innerHTML += "</table><br/><button onclick='window.print()'>Print</button>";
}
//window.onload = createTable();
window.addEventListener('load', createTable(), false);
</script>
i have tried this and this, but still not working
if i use document.write for the whole page instead, the links in the page does not work
Try this
window.onload = () => {
createTable()
}
The second argument in addEventListener method should be a function.
In your code, you called the function createTable as the second argument and the result of that function is not a function. You can fix that by removing the call parenthesis like so:
window.addEventListener('load', createTable, false);
This way you will pass the actual createTable method.
In addition you have a typo in the function name of document.getElementsById("content") it should be document.getElementById("content") since you get only one element by id.

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>");
}
}

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

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