facing issues while Displaying Json data in to dynamic tabs using Javascript - javascript

I am trying following code to display the tabs and tab content from Json data dynamically
<script>
var area, cus, project, curst;
$.ajax({
type: "POST",
url: "./QuizServlet",
success: function(responseText) {
console.log("rs" + responseText.toString());
var jsonData = JSON.parse(responseText);
var questions = new Array();
for (var i = 0; i < jsonData.length; i++) {
area = jsonData[i].area;
console.log("area" + area);
project = jsonData[i].projectName;
console.log("poj" + project);
projectdes = jsonData[i].projectDescription;
console.log("pojdes" + projectdes);
curst = jsonData[i].currentStatus;
console.log("cus" + curst);
var test = {
area: area,
cus: curst,
project: project,
projectdes: projectdes,
}
questions.push(test);
console.log("output" + test);
alert(JSON.stringify(test));
}
}
});
for (var i in test) {
$('.nav-tabs').append('<li role="area" class="">' + i + '</li>');
var div = '<div role="tabpanel" class="tab-pane" area="' + i + '">';
for (var j = 0; j < data[i].length; j++) {
var obj = data[i][j];
div += '<div area="' + obj.project + '">' + obj.projectdes + '</div>';
}
$('.tab-content').append(div);
}
$('.nav-tabs li').eq(0).addClass('active');
$('.tab-content div').eq(0).addClass('active');
</script>
<body>
<div class="container">
<ul class="nav nav-tabs" role="tablist"></ul>
<div class="tab-content"></div>
</div>
</body>
My Json data is coming correctly in JSON format from DB: Below data is coming fine from DB . I printed using alert statement
{"area":"CSE","cus":"progress","project":"Project 1","projectdes":"Class 1st"}
{"area":"ECE","cus":"complered","project":"Project 2","projectdes":"This is class 1st Project"}
{"area":"IT","cus":"progress","project":"project 1","projectdes":"This is Class 2nd project"}
{"area":"IT","cus":"pending","project":"Project 2","projectdes":"This is class 2nd project"}
I am trying to display area in tabs and other fields in tab content.But
the data is not getting displayed in jsp. I tried so many ways.But still data is not getting in tabs and tabs content. Please let me know where I am going wrong.

I updated the answer, you can replace the part of your <script> tag by the code below. And to make the UI feel better, modify the HTML and DOM part as per the UI frameworks like bootstrap, etc.
<script>
$.ajax({
type: "POST",
url: "./QuizServlet",
success: function (responseText) {
var jsonData = JSON.parse(responseText);
var uniueTabs = getUniqueLists(jsonData);
for (var i = 0; i < uniueTabs.length; i++) {
$('.nav-tabs').append('<li role="area" class="my-li' + i + '"><a href="#' + i +
'" aria-controls="' + i + '" role="tab" data-toggle="tab">' + uniueTabs[i].area +
'</a></li>');
var div = '<div role="tabpanel" class="tab-pane" area="' + i + '">';
for (var j = 0; j < uniueTabs[i].tabContent.length; j++) {
var obj = uniueTabs[i].tabContent[j];
div += '<div area="' + obj.project + '">' + obj.projectdes + '</div>';
}
$('.my-li' + i).append(div);
}
$('.nav-tabs li').eq(0).addClass('active');
$('.tab-content div').eq(0).addClass('active');
}
});
function getUniqueLists(responseText) {
var resArr = [];
responseText.filter(function (x, i) {
if (resArr.indexOf(x.area) === -1) {
resArr.push(x.area);
}
})
//console.log(resArr);
return mergeDataAreaWise(resArr, responseText);
}
function mergeDataAreaWise(area, responseText) {
var tabList = [];
for (var i = 0; i < area.length; i++) {
tabList.push({
area: area[i],
tabContent: []
});
}
for (var i = 0; i < tabList.length; i++) {
for (var j = 0; j < responseText.length; j++) {
var Obj = {
cus: responseText[j].cus,
project: responseText[j].project,
projectdes: responseText[j].projectdes
}
var currentArea = responseText[j].area;
if (tabList[i].area === currentArea) {
tabList[i].tabContent.push(Obj);
}
}
}
console.log(tabList);
return tabList;
}
</script>
Here is a similar plunkr example

Related

how to fix if .media$thumbnail.url not found?

I'm Building a widget for blogger
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postSummary = json.feed.entry[i].summary.$t;
var Thumb = json.feed.entry[i].media$thumbnail.url;
var item = '<div class="wrapper"><img src='+ Thumb +' /><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><p>' + postSummary + '</p></div>';
document.write(item);
}
}
</script>
<script src="https://smag-soratemplates.blogspot.com/feeds/posts/summary?max-results=5&alt=json-in-script&callback=mycallback"></script>
but if there is no image in the post or cant find .media$thumbnail.url
the widget stops working , anyone know how to fix that ? or to show an alternative image?
sorry i'm a beginner
If it's failing when the thumbnail does not exist, then you can put a check for the thumbnail
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postSummary = json.feed.entry[i].summary.$t;
var Thumb = json.feed.entry[i].media$thumbnail.url;
if( typeof Thumb == "undefined" ) {
Thumb = '/Your custom image url';
}
var item = '<div class="wrapper"><img src='+ Thumb +' /><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><p>' + postSummary + '</p></div>';
document.write(item);
}
}
</script>
<script src="https://smag-soratemplates.blogspot.com/feeds/posts/summary?max-results=5&alt=json-in-script&callback=mycallback"></script>
You need to use or(||) in the Thumb definition like that
var Thumb = json.feed.entry[i].media$thumbnail.url || 'https://i.imgur.com/5WMAvAu.gif';
Here, if json.feed.entry[i].media$thumbnail.url is undefine/false/null, Thumb is set to 'https://i.imgur.com/5WMAvAu.gif' as your default image.
You need to check that all of the values are present:
json.feed.entry[i].media$thumbnail.url
as any of these items could be null / undefined:
json
json.feed
json.feed.entry[i]
json.feed.entry[i].media$thumbnail
json.feed.entry[i].media$thumbnail.url
At the least, you should check:
if(json.feed.entry[i].media$thumbnail && json.feed.entry[i].media$thumbnail.url)
Also, it's probably worth rewriting this code as follows:
let entry = json.feed.entry[i];
to save yourself some typing (and to stop all the object look ups each time when using dots to reference nested objects).
The code then becomes:
let url = '';
if (entry.media$thumbnail && media$thumbnail.url) {
url = entry.media$thumbnail.url;
}
else {
url = 'the default image URL';
}
Thank you all i found the solution
by replacing this code
var Thumb = json.feed.entry[i].media$thumbnail.url;
with this code
if (json.feed.entry[i].media$thumbnail)
{
Thumb = json.feed.entry[i].media$thumbnail.url;
}
else
{
Thumb= "'Image url'";
}

JavaScript: Cannot read property 'value' of null from textbox

function create(param) {
var i, target = document.getElementById('results');
target.innerHTML = '';
for(i = 1; i <= param; i += 1) {
target.innerHTML +='<br>'
for(var j=1;j<=param;j+=1)
target.innerHTML += '<input type="text" id="a'+i+''+j+'" placeholder="a'+i+''+j+'">';
}
}
function saveData(param) {
var a = []
for(var i = 1;i<param;i+=1) {
a[i] = [];
for(var j = 1;j<param;j+=1)
a[i][j] = document.getElementById('"a'+i+''+j+'"').value;
}
var target = document.getElementById('ShowResults');
for(var i = 1;i<param;i+=1){
a[i] = [];
target.innerHTML +='<br>'
for(var j = 1;j<param;j+=1)
target.innerHTML +=a[i][j];
}
}
<button onclick="create(5)" style="widht:300px;height:30px;">Create table</button>
<div id="results"> </div>
<button id="takeResults" onclick="saveData(5)"style="widht:300px;height:30px;">Save data</button>
<div id="ShowResults"> </div>
Ok so i made a table whit js and gave every textbox id of "a'+i+''+j+'" but it seems that when i want to save the data it show's me the following error: Cannot read property 'value' of null
Can you guys tell me what i did wrong?
Here's the solution with some code improvements
As i said in the comment, you had a mistake in the code you getElementById('"a' + i + '' + j + '"') should be getElementById('a' + i + '' + j)
and there's a lot of unnecessary loops
function create(param) {
var target = document.getElementById('results');
target.innerHTML = '';
for (var i = 0; i < param; i++) {
target.innerHTML += '<br>'
for (var j = 0; j < param; j++)
target.innerHTML += '<input type="text" id="a' + i + '' + j + '" placeholder="a' + i + '' + j + '">';
}
}
function saveData(param) {
var target = document.getElementById('ShowResults');
target.innerHTML = '';
var a = []
for (var i = 0; i < param; i++) {
a[i] = [];
for (var j = 0; j < param; j++) {
target.innerHTML += document.getElementById('a' + i + '' + j).value;
}
target.innerHTML += '<br>'
}
}
<button onclick="create(5)" style="widht:300px;height:30px;">Create table</button>
<div id="results"> </div>
<button id="takeResults" onclick="saveData(5)" style="widht:300px;height:30px;">Save data</button>
<div id="ShowResults"> </div>
Change this...
a[i][j] = document.getElementById('"a'+i+''+j+'"').value;
to this...
a[i][j] = document.getElementById('a' + i + j).value;
You have two lots of quotes around the id when you create it, but you don't need to add them both when you're using getElementById. Just build the string and it will work.
There were some other issues with your code, mainly where you didn't have opening braces but you had closing braces. Copy/paste this and it should fix your issues...
function create(param) {
var i, target = document.getElementById('results');
target.innerHTML = '';
for(i = 1; i <= param; i += 1) {
target.innerHTML +='<br>'
for(var j=1;j<=param;j+=1) {
target.innerHTML += '<input type="text" id="a'+i+''+j+'" placeholder="a'+i+''+j+'">';
}
}
function saveData(param) {
var a = []
for(var i = 1;i<param;i+=1) {
a[i] = [];
for(var j = 1;j<param;j+=1) {
a[i][j] = document.getElementById('a' + i + j).value;
}
var target = document.getElementById('ShowResults');
for(var i = 1;i<param;i+=1) {
a[i] = [];
target.innerHTML +='<br>'
for(var j = 1;j<param;j+=1) {
target.innerHTML +=a[i][j];
}
}
}
}
Incidentally, using multiple layers of arrays can cause issues, mainly due to being unfriendly for the reader (or you in the future). I'd highly recommend using an array of objects instead, and naming things more appropriately than a, i & j.

Javascript how to define an object by array of objects

I recently started learning html/javascript and I want a temporary object to be filled with one of the objects from an array based on the current page number.
loadnextpage();
function loadnextpage() {
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' + curpage.title);
}
But when I try to run the code it keeps giving me an error message that curpage is undefined, after that it keeps running and thus the last line of code gives an error, when I ask for curpage.pageNumber. After that it stops running the code.
image clipping of my code with error message
What am I doing wrong?
edit:
here is the entire code:
var pagenumber = 0;
var receipt = [];
var price = 0;
var text = '{"page": [{"pageNumber": "1","title": "kies je formaat","optionName": "size","option": [{"text": "klein","value": "small","extraPrice": "100"},{"text": "middel","value": "medium","extraPrice": "200"},{"text": "groot","value": "large","extraPrice": "300"}]},{"pageNumber": "2","title": "kies je kleur","optionName": "colour","option": [{"text": "rood","value": "red","extraPrice": "10"},{"text": "groen","value": "green","extraPrice": "20"},{"text": "blauw","value": "blue","extraPrice": "30"}]}]}';
var allcontent = [];
allcontent = JSON.parse(text);
var imgpath = 'img/';
loadnextpage();
function loadnextpage(){
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' +
curpage.title);
var radiobuttons = '';
var radiobuttonid = [];
for(var i = 0; i < curpage.option.length; i++) {
var curradio = curpage.option[i];
radiobuttons += '<label><div class="selection-wrap">';
radiobuttons += curradio.text;
radiobuttons += ' <input type="radio" name="';
radiobuttons += curpage.optoinName;
radiobuttons += '" value="';
radiobuttons += curradio.value;
radiobuttons += '" id="';
radiobuttons += curpage.optoinName;
radiobuttons += '_';
radiobuttons += curradio.value;
radiobuttons += '"></div></label></br>';
radiobuttonid.push(curpage.optoinName + '_' + curradio.value)
}
changeDiv('choices', radiobuttons);
for(var i = 0; i < radiobuttonid.length; i++){
document.getElementById(radiobuttonid[i]).onclick = function(){
receipt[pagenumber-1] = curpage.option[i];
for(var i = 0; i < receipt.length; i++){
price += receipt[i].extraPrice;
}
changeImg('previewimg', imgpath + curpage.option[i].value +
'/preview.jpg');
changeDiv('previewprice', '<h1>€' + price + ',-</h1>');
};
}
};
function changeDiv(id, content) {
document.getElementById(id).innerHTML = content;
};
function changeImg(id, img){
document.getElementById(id).src = img;
};

Same name inserting again and again in the the dropdown list when click on tab button

I am using my function in onclick nav tabs event (when click on any tab this below function activates). I just want that no same name can twice be inserted into the dropdownlist. Below function is working just perfectly. I just need a check maybe like name.text != arr[i] something like that to prevent it to insert the same name twice in the list. Any help would be appreciated.
js:
<script>
$(".nav-tabs li").click
(
function()
{
var getnumber = document.getElementById("permanentno").value;
var getData = 'methodname=getList&no='+getnumber;
$.ajax
({
type: 'GET',
url: 'Dropdown List/List.php',
data: getData,
success: function(resp)
{
alert(resp); // names for example: mile,stone,
var arr = resp.split(",");
var list = $(".dropdownlist");
var html = "";
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
}
}
$(".dropdownlist").append(html);
}
});
}
);
</script>
You could keep track of the names with another array and IndexOf. Note that for IE<9 support you'll need a shiv to use it.
var names = [];
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0 && names.indexOf(name) == -1)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
names.push(name);
}
}
You can append options to the dropdownlist on the loop, and check repeated names using jQuery like:
var list = $(".dropdownlist");
for (var i = 0; i < arr.length; i++) {
var name = arr[i];
if (name.length != 0 && !list.find("option[value='" + name + "']").length) {
var html = "<option value='" + name + "'>";
html += name;
html += "</option>";
list.append(html);
}
}

Javascript Hanging UI on IE6/7

Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?

Categories

Resources