I am working on a spring boot web application. I have a page where I need to show star rating system. Number of rating is stored in database. Format is: 1, 1.5, 2, 2.5...up to 5. I want to convert these numbers into stars. How should I do that after getting ajax response success from MySql DB.
function getreview() {
var productid = document.getElementById('pid').value;
var url = "/api/getcustomerreview";
$.post(url, {
productid : productid,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
var div = "", des = "";
var list = data.response;
var listlength = list.length;
if(listlength > 0){
for(var i = 0; i < listlength; i++) {
var rating = list[i].reviewrating;
var stars = "";
console.log("Customer review rating: "+rating); // for product id
15 there is rating number 5 and 4
div = div + "<div class=\"row\"><div class=\"col-lg-7\"><div class=\"review-wrapper\"><div class=\"single-review\"><div class=\"review-img\">"
+"<img src=\"public/web/assets/images/1.png\" alt=\"\"/></div><div class=\"review-content\">"
+"<div class=\"review-top-wrap\"><div class=\"review-left\"><div class=\"review-name\">"
+"<h4>"+list[i].customername+"</h4></div><div class=\"rating-product\"><i class=\"ion-android-star\"></i>"
+"</div></div><div class=\"review-left\">Reply</div>"
+"</div><div class=\"review-bottom\"><p>"+list[i].reviewmessage+"</p></div></div></div>"
+"<div class=\"single-review child-review\"><div class=\"review-img\">\<img src=\"public/web/assets/images/2.png\" alt=\"\"/>\</div>"
+"<div class=\"review-content\"><div class=\"review-top-wrap\"><div class=\"review-left\"><div class=\"review-name\">"
+"<h4>"+list[i].customername+"</h4></div><div class=\"rating-product\"><i class=\"ion-android-star\"></i>"
+"</div></div><div class=\"review-left\">Reply</div>"
+"</div><div class=\"review-bottom\"><p>"+list[i].reviewmessage+"</p></div></div></div>"
+"</div></div></div>";
document.getElementById('des-details3').innerHTML = div;
}
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
Below is div tag is to display star according to rating number that has been stored in database.
<div class=\"rating-product\"><i class=\"ion-android-star\"></i></div>
You can simply use for-loop with rating as counter end value then on each iteration append your icon in some variable using += and finally append this inside html which is already generated .
Demo Code :
var div = "",
des = "";
//just for demo
var list = [{
"customername": "abc",
"reviewmessage": "Good",
"reviewrating": 4.5
}, {
"customername": "xyz",
"reviewmessage": "Very good",
"reviewrating": 5
}, {
"customername": "xyz",
"reviewmessage": "Very good",
"reviewrating": 3.5
}] //data.response;
var listlength = list.length;
if (listlength > 0) {
for (var i = 0; i < listlength; i++) {
var rating = parseInt(list[i].reviewrating);
var stars = "";
//loop through rating...no
for (var j = 1; j <= rating; j++) {
stars += '<i class="fas fa-star" style="color:gold"></i>'; //append new star on each iteration..
}
//check if there is `.` in number..means .5
if (list[i].reviewrating.toString().indexOf('.') != -1) {
//half star
stars += '<i class="fas fa-star-half-alt" style="color:gold"></i>'
}
//pass them here
div = div + "<div class=\"row\"><div class=\"col-lg-7\"><div class=\"review-wrapper\"><div class=\"single-review\"><div class=\"review-img\">" +
"<img src=\"public/web/assets/images/1.png\" alt=\"\"/></div><div class=\"review-content\">" +
"<div class=\"review-top-wrap\"><div class=\"review-left\"><div class=\"review-name\">" +
"<h4>" + list[i].customername + "</h4></div><div class=\"rating-product\">" + stars +
"</div></div><div class=\"review-left\">Reply</div>" +
"</div><div class=\"review-bottom\"><p>" + list[i].reviewmessage + "</p></div></div></div>" +
"<div class=\"single-review child-review\"><div class=\"review-img\">\<img src=\"public/web/assets/images/2.png\" alt=\"\"/>\</div>" +
"<div class=\"review-content\"><div class=\"review-top-wrap\"><div class=\"review-left\"><div class=\"review-name\">" +
"<h4>" + list[i].customername + "</h4></div><div class=\"rating-product\">" + stars +
"</div></div><div class=\"review-left\">Reply</div>" +
"</div><div class=\"review-bottom\"><p>" + list[i].reviewmessage + "</p></div></div></div>" +
"</div></div></div>";
document.getElementById('des-details3').innerHTML = div;
}
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/fontawesome.min.css" integrity="sha512-OdEXQYCOldjqUEsuMKsZRj93Ht23QRlhIb8E/X0sbwZhme8eUw6g8q7AdxGJKakcBbv7+/PX0Gc2btf7Ru8cZA==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<div id="des-details3"> </div>
Other way you can use star-rating-svg plugin to achieve this . So, you just need to initialize them with the value of rating .
Demo Code :
var div = "",
des = "";
//just for demo
var list = [{
"customername": "abc",
"reviewmessage": "Good",
"reviewrating": 4.5
}, {
"customername": "xyz",
"reviewmessage": "Very good",
"reviewrating": 5
}, {
"customername": "xyz",
"reviewmessage": "Very good",
"reviewrating": 3.5
}] //data.response;
var listlength = list.length;
if (listlength > 0) {
$("#des-details3").empty()
for (var i = 0; i < listlength; i++) {
var rating = parseFloat(list[i].reviewrating);
div = "<div class=\"row\"><div class=\"col-lg-7\"><div class=\"review-wrapper\"><div class=\"single-review\"><div class=\"review-img\">" +
"<img src=\"public/web/assets/images/1.png\" alt=\"\"/></div><div class=\"review-content\">" +
"<div class=\"review-top-wrap\"><div class=\"review-left\"><div class=\"review-name\">" +
"<h4>" + list[i].customername + "</h4></div><div class=\"rating-product\"></div></div><div class=\"review-left\">Reply</div>" +
"</div><div class=\"review-bottom\"><p>" + list[i].reviewmessage + "</p></div></div></div>" +
"<div class=\"single-review child-review\"><div class=\"review-img\">\<img src=\"public/web/assets/images/2.png\" alt=\"\"/>\</div>" +
"<div class=\"review-content\"><div class=\"review-top-wrap\"><div class=\"review-left\"><div class=\"review-name\">" +
"<h4>" + list[i].customername + "</h4></div><div class=\"rating-product\"></div></div><div class=\"review-left\">Reply</div>" +
"</div><div class=\"review-bottom\"><p>" + list[i].reviewmessage + "</p></div></div></div>" +
"</div></div></div>";
$("#des-details3").append(div) //append your div
//then intialize your rating...
$("#des-details3 .row:last .rating-product").starRating({
initialRating: rating,
strokeColor: '#894A00',
strokeWidth: 10,
starSize: 25
});
}
}
.rating-product {
pointer-events: none/*use this if you don't want user to change rating*/
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/star-rating-svg#3.5.0/src/css/star-rating-svg.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/star-rating-svg#3.5.0/src/jquery.star-rating-svg.js"></script>
<div id="des-details3"> </div>
Use array.fill() then convert the array to text:
const s5 = ["\u2606", "\u2606","\u2606", "\u2606", "\u2606"];
s5.fill('\u2B50',0,rating);
s5text = s5.join("");
I have 3 elements arranged in a row. I want to show a carousel pop-up on click of the columns in the row. The issue is I am not able to change the images of carousal based on selected column element.
Here is my complete code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
width: 70%;
margin: auto;
}
</style>
</head>
<script>
function process() {
var shops = JSON.parse('{ "id": "shopping", "categories": [ { "id": "Amazon", "name": "Amazon", "link": "https://images-na.ssl-images-amazon.com/images/G/01/SellerCentral/legal/amazon-logo_transparent._CB303899249_.png", "images": [ { "href": "https://images-na.ssl-images-amazon.com/images/G/01/credit/img16/CBCC/marketing/marketingpage/products._V524365396_.png" }, { "href": "http://static4.uk.businessinsider.com/image/575adbe2dd0895c4098b46ba/the-50-most-popular-products-on-amazon.jpg" } ] }, { "id": "Google", "name": "Google", "link": "http://pngimg.com/uploads/google/google_PNG19644.png", "images": [ { "href": "https://www.clipartmax.com/png/middle/147-1476512_google-google-products-logos-png.png" }, { "href": "https://xvp.akamaized.net/assets/illustrations/unblock-google/unblock-google-with-a-vpn-fc1e32f59d9c50bae315c2c8506a91e2.png" } ] }, { "id": "Apple", "name": "Apple", "link": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Apple_Logo.svg/2000px-Apple_Logo.svg.png", "images": [ { "href": "https://c.slashgear.com/wp-content/uploads/2018/03/apple-mfi-logos-update-2018-980x620.jpg" }, { "href": "https://support.apple.com/library/content/dam/edam/applecare/images/en_US/applemusic/itunes-apple-logo-apple-music-giftcard.jpg" } ] } ] }');
var row = 1;
var content = "";
shops = shops.categories;
for(var i=0; i< shops.length; i++) {
if(row == 1) {
content += '<div class="row">'
}
content += '<div class="col-md-4 col-sm-12" data-toggle="modal" onclick="processCarousel(shops[i])" data-target="#myModal">';
content += '<img style="border: 1px solid red" src="'+shops[i].link+'" width="100%" height="100%"/></div>';
if(row == 3) {
row = 0;
content += '</div>';
}
row++;
}
document.getElementById("placeholder").innerHTML = content;
processCarousel();
}
function processCarousel(input) {
alert(input);
var m = ['img_chania.jpg','img_chania2.jpg', 'img_flower.jpg','img_flower2.jpg'];
var carouselInner = document.getElementById("carousel-inner");
var carouselIndicators = document.getElementById("carousel-indicators");
var innerContent = "";
var indicatorsContent = "";
for(var i=0 ; i< m.length ; i++) {
var c = "";
if(i == 0) {
c = " active";
}
innerContent += '<div class="item'+c+'"><img src="'+m[i]+'"><div class="carousel-caption"></div> </div>';
indicatorsContent += '<li class='+c+'data-target="#carousel-example-generic" data-slide-to="'+i+'"></li>';
}
carouselInner.innerHTML = innerContent;
carouselIndicators.innerHTML = indicatorsContent;
var carouselExampleGeneric = document.getElementById("carousel-example-generic");
carouselExampleGeneric.carousel();
}
</script>
</html>
The above code generates the below output:
On click of any image it is loading the carousal but the images of carousal are fixed to my array elements var m = ['img_chania.jpg','img_chania2.jpg', 'img_flower.jpg','img_flower2.jpg']; as mentioned in my above code.
But I want to show only the selected images which are present in my input json shops.categories[selectedItem].images
I tried using onclick javascript event on column element, but the code is not recognising it. What is the correct way to do this.
I want to do this using plain javascript.
First you need to get rid of the call to processCarousel(); in line 39.
Your main problem is, that inside of your content variable you are passing the string of the argument variable rather than the argument itself. Try this instead:
content += '<div class="col-md-4 col-sm-12" data-toggle="modal" onclick="processCarousel(' + i + ')" data-target="#myModal">';
This way you are just passing the index of the category that needs to be rendered.
Then you will have to have the shops object available inside of the processCarousel function as well, so I moved it up, outside the function scope.
This will result in further problems inside of you processCarousel function. You will have to set your your images like this var m = shops[i].images; instead of var m = ['img_chania.jpg', 'img_chania2.jpg', 'img_flower.jpg', 'img_flower2.jpg'];
This will throw another error further down.
innerContent += '<div class="item' + c + '"><img src="' + m[i] + '"><div class="carousel-caption"></div> </div>'; will not work. Instead you will have to use m[i].href as your source inside your image tag.
This will now pass the config to the Carousel which will then render just fine.
You might want to think about giving variables speaking names and avoiding variables like 'm'.
var shops = JSON.parse('{ "id": "shopping", "categories": [ { "id": "Amazon", "name": "Amazon", "link": "https://images-na.ssl-images-amazon.com/images/G/01/SellerCentral/legal/amazon-logo_transparent._CB303899249_.png", "images": [ { "href": "https://images-na.ssl-images-amazon.com/images/G/01/credit/img16/CBCC/marketing/marketingpage/products._V524365396_.png" }, { "href": "http://static4.uk.businessinsider.com/image/575adbe2dd0895c4098b46ba/the-50-most-popular-products-on-amazon.jpg" } ] }, { "id": "Google", "name": "Google", "link": "http://pngimg.com/uploads/google/google_PNG19644.png", "images": [ { "href": "https://www.clipartmax.com/png/middle/147-1476512_google-google-products-logos-png.png" }, { "href": "https://xvp.akamaized.net/assets/illustrations/unblock-google/unblock-google-with-a-vpn-fc1e32f59d9c50bae315c2c8506a91e2.png" } ] }, { "id": "Apple", "name": "Apple", "link": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Apple_Logo.svg/2000px-Apple_Logo.svg.png", "images": [ { "href": "https://c.slashgear.com/wp-content/uploads/2018/03/apple-mfi-logos-update-2018-980x620.jpg" }, { "href": "https://support.apple.com/library/content/dam/edam/applecare/images/en_US/applemusic/itunes-apple-logo-apple-music-giftcard.jpg" } ] } ] }');
var row = 1;
var content = "";
shops = shops.categories;
function process() {
for (var i = 0; i < shops.length; i++) {
if (row == 1) {
content += '<div class="row">'
}
content += '<div class="col-md-4 col-sm-12" data-toggle="modal" onclick="processCarousel(' + i + ')" data-target="#myModal">';
content += '<img style="border: 1px solid red" src="' + shops[i].link + '" width="100%" height="100%"/></div>';
if (row == 3) {
row = 0;
content += '</div>';
}
row++;
}
document.getElementById("placeholder").innerHTML = content;
}
function processCarousel(i) {
//var m = ['img_chania.jpg', 'img_chania2.jpg', 'img_flower.jpg', 'img_flower2.jpg'];
var m = shops[i].images;
var carouselInner = document.getElementById("carousel-inner");
var carouselIndicators = document.getElementById("carousel-indicators");
var innerContent = "";
var indicatorsContent = "";
for (var i = 0; i < m.length; i++) {
var c = "";
if (i == 0) {
c = " active";
}
innerContent += '<div class="item' + c + '"><img src="' + m[i].href + '"><div class="carousel-caption"></div> </div>';
indicatorsContent += '<li class=' + c + 'data-target="#carousel-example-generic" data-slide-to="' + i + '"></li>';
}
carouselInner.innerHTML = innerContent;
carouselIndicators.innerHTML = indicatorsContent;
var carouselExampleGeneric = document.getElementById("carousel-example-generic");
//carouselExampleGeneric.carousel();
}
I am doing an exercise related with JSON and JavaScript. However, I just could not figure out that what's wrong with my syntax. It should show the links on the ordered list part in HTML, but I got only H2 tag.
Here is the syntax:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Javascript and jason</title>
</head>
<body>
<h2>Links</h2>
<ol id="links">
</ol>
<script>
var info = {
"full_name":"Ray Villaobos",
"title" : "Staff Author",
"links" :[
{"blog":"http://iviewsource.com"},
{"facebook":"http://facebook.com/iviewsource"},
{"youtube":"http://www.youtube.com"},
{"podcast":"http://feeds.feedburer.com/authoredcontent"},
{"twitter":"http://twitter.com/planetoftheweb"}
]
};
var output = '';
for (var i=0; i <=info.links.length; i++) {
for (key in info.links[i]){
if (info.links[i].hasOwnProperty(key))
{
output +='<li>' +
'<a href ="' + info.links[i][key]+
'">' +'</a>' +
'<li>';
}
}
}
var update = document.getElementById('links');
update.innerHtml = output;
</script>
</body>
</html>
You don't see anything because you have a typo. Remember that JavaScript is case-sensitive.
It should be :
update.innerHTML = output;
So with uppercase HTML.
But it might be better to use appendChild like so:
var output = '';
var update = document.getElementById('links');
for (var i = 0; i <= info.links.length; i++) {
for (key in info.links[i]) {
if (info.links[i].hasOwnProperty(key)) {
var li = document.createElement('li');
var a = document.createElement('a');
a.setAttribute('href', info.links[i][key]);
a.text = key;
li.appendChild(a);
update.appendChild(li);
}
}
}
See Fiddle
Three problems:
You're not closing your li elements; you have another <li> where the closing </li> should be.
You're not putting anything inside the <a> tags. I'm including key as the link text here.
innerHtml should be innerHTML.
var info = {
"full_name": "Ray Villaobos",
"title": "Staff Author",
"links": [{
"blog": "http://iviewsource.com"
}, {
"facebook": "http://facebook.com/iviewsource"
}, {
"youtube": "http://www.youtube.com"
}, {
"podcast": "http://feeds.feedburer.com/authoredcontent"
}, {
"twitter": "http://twitter.com/planetoftheweb"
}]
};
var output = '';
for (var i = 0; i <= info.links.length; i++) {
for (key in info.links[i]) {
if (info.links[i].hasOwnProperty(key)) {
output += '<li>' +
'<a href="' + info.links[i][key] +
'">' + key + '</a>' +
'</li>';
}
}
}
var update = document.getElementById('links');
update.innerHTML = output;
<h2>Links</h2>
<ol id="links">
</ol>
I've a list that autopopulates from a JSON file:
<div class="conversionFormES" id="from1">
<label for="from">Convert From:</label>
<select size = "10" name="from" id="from" onchange="convertUnits()">
<option value="from">-Select an Option-</option>
<option value="from">Firefox</option>
</select>
</div>
I added the 'Firefox' option just to make sure something was being displayed and it is.
Any ideas what the problem could be. Just to re-iterate, it works perfectly with chrome and safari. Many thanks.
ConvertUnits function:
function convertUnits(){
var convertObj = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
var measurementType = $("#from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(convertObj.units.val());
// convertObj.convertUnitsFromHash();
if(measurementType == "temp"){
convertObj.convertTemp();
}else{
convertObj.convertUnitsFromHash();
}
console.log('Measurement Type:', measurementType);
}
JSON Script called after the HTML Form.
<script>
// JSON:
// The key is the class identifier, temp, area etc etc
// Value is being used for both ID and Value when the list is being populated
$(document).ready(function(){
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
});
</script>
EDIT: JSON sample:
{
"angle": [
{
"value": "degree",
"name": "Degree(deg)"
},
{
"value": "radian",
"name": "Radian(rad)"
}
]
}
I have on page div:
<div id="here_table"></div>
and in jquery:
for(i=0;i<3;i++){
$('#here_table').append( 'result' + i );
}
this generating for me:
<div id="here_table">
result1 result2 result3 etc
</div>
I would like receive this in table:
<div id="here_table">
<table>
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</table>
</div>
I doing:
$('#here_table').append( '<table>' );
for(i=0;i<3;i++){
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append( '</table>' );
but this generate for me:
<div id="here_table">
<table> </table> !!!!!!!!!!
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</div>
Why? how can i make this correctly?
LIVE: http://jsfiddle.net/n7cyE/
This line:
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
Appends to the div#here_table not the new table.
There are several approaches:
/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
content += '<tr><td>' + 'result ' + i + '</td></tr>';
}
content += "</table>"
$('#here_table').append(content);
But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.
But how about this one, it does what you expect nearly great:
var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
var row = $('<tr>').addClass('bar').text('result ' + i);
table.append(row);
}
$('#here_table').append(table);
Hope this would help.
You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because it is not necessary.
$('#here_table').append( '<table />' );
for(i=0;i<3;i++){
$('#here_table table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
The main problem was that you were appending the tr to the div here_table.
Edit: Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop
var doc = document;
var fragment = doc.createDocumentFragment();
for (i = 0; i < 3; i++) {
var tr = doc.createElement("tr");
var td = doc.createElement("td");
td.innerHTML = "content";
tr.appendChild(td);
//does not trigger reflow
fragment.appendChild(tr);
}
var table = doc.createElement("table");
table.appendChild(fragment);
doc.getElementById("here_table").appendChild(table);
When you use append, jQuery expects it to be well-formed HTML (plain text counts). append is not like doing +=.
You need to make the table first, then append it.
var $table = $('<table/>');
for(var i=0; i<3; i++){
$table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append($table);
Or do it this way to use ALL jQuery. The each can loop through any data be it DOM elements or an array/object.
var data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
var numCols = 1;
$.each(data, function(i) {
if(!(i%numCols)) tRow = $('<tr>');
tCell = $('<td>').html(data[i]);
$('table').append(tRow.append(tCell));
});
http://jsfiddle.net/n7cyE/93/
To add multiple columns and rows, we can also do a string concatenation. Not the best way, but it sure works.
var resultstring='<table>';
for(var j=0;j<arr.length;j++){
//array arr contains the field names in this case
resultstring+= '<th>'+ arr[j] + '</th>';
}
$(resultset).each(function(i, result) {
// resultset is in json format
resultstring+='<tr>';
for(var j=0;j<arr.length;j++){
resultstring+='<td>'+ result[arr[j]]+ '</td>';
}
resultstring+='</tr>';
});
resultstring+='</table>';
$('#resultdisplay').html(resultstring);
This also allows you to add rows and columns to the table dynamically, without hardcoding the fieldnames.
Here is what you can do: http://jsfiddle.net/n7cyE/4/
$('#here_table').append('<table></table>');
var table = $('#here_table').children();
for(i=0;i<3;i++){
table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
Best regards!
Following is done for multiple file uploads using jquery:
File input button:
<div>
<input type="file" name="uploadFiles" id="uploadFiles" multiple="multiple" class="input-xlarge" onchange="getFileSizeandName(this);"/>
</div>
Displaying File name and File size in a table:
<div id="uploadMultipleFilediv">
<table id="uploadTable" class="table table-striped table-bordered table-condensed"></table></div>
Javascript for getting the file name and file size:
function getFileSizeandName(input)
{
var select = $('#uploadTable');
//select.empty();
var totalsizeOfUploadFiles = "";
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size; // file size in bytes
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2); // convert the file size from bytes to mb
var filename = input.files[i].name;
select.append($('<tr><td>'+filename+'</td><td>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles = totalsizeOfUploadFiles+filesizeInMB;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
}
}
Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu"> on any page to reproduce the HTML.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML Masterpage</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function nav() {
var menuHTML= '<ul><li>link 1</li></ul><ul><li>link 2</li></ul>';
$('#menu').append(menuHTML);
}
</script>
<style type="text/css">
</style>
</head>
<body onload="nav()">
<div id="menu"></div>
</body>
</html>
I wrote rather good function that can generate vertical and horizontal tables:
function generateTable(rowsData, titles, type, _class) {
var $table = $("<table>").addClass(_class);
var $tbody = $("<tbody>").appendTo($table);
if (type == 2) {//vertical table
if (rowsData.length !== titles.length) {
console.error('rows and data rows count doesent match');
return false;
}
titles.forEach(function (title, index) {
var $tr = $("<tr>");
$("<th>").html(title).appendTo($tr);
var rows = rowsData[index];
rows.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
} else if (type == 1) {//horsantal table
var valid = true;
rowsData.forEach(function (row) {
if (!row) {
valid = false;
return;
}
if (row.length !== titles.length) {
valid = false;
return;
}
});
if (!valid) {
console.error('rows and data rows count doesent match');
return false;
}
var $tr = $("<tr>");
titles.forEach(function (title, index) {
$("<th>").html(title).appendTo($tr);
});
$tr.appendTo($tbody);
rowsData.forEach(function (row, index) {
var $tr = $("<tr>");
row.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
}
return $table;
}
usage example:
var title = [
'مساحت موجود',
'مساحت باقیمانده',
'مساحت در طرح'
];
var rows = [
[number_format(data.source.area,2)],
[number_format(data.intersection.area,2)],
[number_format(data.deference.area,2)]
];
var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");
$ft.appendTo( GroupAnalyse.$results );
var title = [
'جهت',
'اندازه قبلی',
'اندازه فعلی',
'وضعیت',
'میزان عقب نشینی',
];
var rows = data.edgesData.map(function (r) {
return [
r.directionText,
r.lineLength,
r.newLineLength,
r.stateText,
r.lineLengthDifference
];
});
var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");
$et.appendTo( GroupAnalyse.$results );
$('<hr/>').appendTo( GroupAnalyse.$results );
example result:
A working example using the method mentioned above and using JSON to represent the data. This is used in my project of dealing with ajax calls fetching data from server.
http://jsfiddle.net/vinocui/22mX6/1/
In your html:
< table id='here_table' >< /table >
JS code:
function feed_table(tableobj){
// data is a JSON object with
//{'id': 'table id',
// 'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
// 'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },... ]}
$('#' + tableobj.id).html( '' );
$.each([tableobj.header, tableobj.data], function(_index, _obj){
$.each(_obj, function(index, row){
var line = "";
$.each(row, function(key, value){
if(0 === _index){
line += '<th>' + value + '</th>';
}else{
line += '<td>' + value + '</td>';
}
});
line = '<tr>' + line + '</tr>';
$('#' + tableobj.id).append(line);
});
});
}
// testing
$(function(){
var t = {
'id': 'here_table',
'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },
{'a': 'Real Estate', 'b' :'Property', 'c' :'$500000' , 'd': 'Edit/Delete' }
]};
feed_table(t);
});
As for me, this approach is prettier:
String.prototype.embraceWith = function(tag) {
return "<" + tag + ">" + this + "</" + tag + ">";
};
var results = [
{type:"Fiat", model:500, color:"white"},
{type:"Mercedes", model: "Benz", color:"black"},
{type:"BMV", model: "X6", color:"black"}
];
var tableHeader = ("Type".embraceWith("th") + "Model".embraceWith("th") + "Color".embraceWith("th")).embraceWith("tr");
var tableBody = results.map(function(item) {
return (item.type.embraceWith("td") + item.model.toString().embraceWith("td") + item.color.embraceWith("td")).embraceWith("tr")
}).join("");
var table = (tableHeader + tableBody).embraceWith("table");
$("#result-holder").append(table);
i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is, imho, a killer feature.
Also the code can be kept cleaner.
$(function(){
var tablerows = new Array();
$.each(['result1', 'result2', 'result3'], function( index, value ) {
tablerows.push('<tr><td>' + value + '</td></tr>');
});
var table = $('<table/>', {
html: tablerows
});
var div = $('<div/>', {
id: 'here_table',
html: table
});
$('body').append(div);
});
Addon: passing more than one "html" tag you've to use array notation like:
e.g.
var div = $('<div/>', {
id: 'here_table',
html: [ div1, div2, table ]
});
best Rgds.
Franz
<table id="game_table" border="1">
and Jquery
var i;
for (i = 0; ii < 10; i++)
{
var tr = $("<tr></tr>")
var ii;
for (ii = 0; ii < 10; ii++)
{
tr.append(`<th>Firstname</th>`)
}
$('#game_table').append(tr)
}
this is most better
html
<div id="here_table"> </div>
jQuery
$('#here_table').append( '<table>' );
for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' + i + '</tr>' );
for(ii=0;ii<3;ii++)
{
$('#here_table').append( '<td>' + 'result' + i + '</tr>' );
}
}
$('#here_table').append( '</table>' );
It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/
In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:
Example #1
ul>li*5
... will produce
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Example #2
div#header+div.page+div#footer.class1.class2.class3
... will produce
<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>
And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/
And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js
Here the below code helps to generate responsive html table
#javascript
(function($){
var data = [{
"head 1": "row1 col 1",
"head 2": "row1 col 2",
"head 3": "row1 col 3"
}, {
"head 1": "row2 col 1",
"head 2": "row2 col 2",
"head 3": "row2 col 3"
}, {
"head 1": "row3 col 1",
"head 2": "row3 col 2",
"head 3": "row3 col 3"
}];
for (var i = 0; i < data.length; i++) {
var accordianhtml = "<button class='accordion'>" + data[i][small_screen_heading] + "<span class='arrow rarrow'>→</span><span class='arrow darrow'>↓</span></button><div class='panel'><p><table class='accordian_table'>";
var table_row = null;
var table_header = null;
for (var key in data[i]) {
accordianhtml = accordianhtml + "<tr><th>" + key + "</th><td>" + data[i][key] + "</td></tr>";
if (i === 0 && true) {
table_header = table_header + "<th>" + key + "</th>";
}
table_row = table_row + "<td>" + data[i][key] + "</td>"
}
if (i === 0 && true) {
table_header = "<tr>" + table_header + "</tr>";
$(".mv_table #simple_table").append(table_header);
}
table_row = "<tr>" + table_row + "</tr>";
$(".mv_table #simple_table").append(table_row);
accordianhtml = accordianhtml + "</table></p></div>";
$(".mv_table .accordian_content").append(accordianhtml);
}
}(jquery)
Here we can see the demo responsive html table generator
let html = '';
html += '<table class="tblWay" border="0" cellpadding="5" cellspacing="0" width="100%">';
html += '<tbody>';
html += '<tr style="background-color:#EEEFF0">';
html += '<td width="80"> </td>';
html += '<td><b>Shipping Method</b></td>';
html += '<td><b>Shipping Cost</b></td>';
html += '<td><b>Transit Time</b></td>';
html += '</tr>';
html += '</tbody>';
html += '</table>';
$('.product-shipping-more').append(html);