I am trying to get indVars to repeat for the amount of times that numInd requires. So if numInd = 3 then I'm wanting something similar to this indVars[0] = divStart + userEntryVars + divEnd -- indVars[1] = divStart + userEntryVars + divEnd ... and so on for however many numInd dictates --- Then the arrays get posted to innerHTML.
/*User Selection Of Indicators*/
var numInd = 3 /*This is amount of indicators that should show in innerHTML.*/
/*User Entry Variables Per Selection*/
var uHeight = 120
var uWidth = 225
/*Html Variables*/
var divStart = '<div class="col-sm-auto">'
var userEntryVars = '<img src="whatever.jpg" style="height:' + uHeight +'px; width: '+ uWidth + 'px">'
var divEnd = '</div>'
/*Div InnerHTML*/
var divArea = document.getElementById("IndicatorArea") ;
var out = []
var indVars = [divStart + userEntryVars + divEnd] ;
/*Loop For Number Of Indicators*/
for (i = 0; i < numInd; i++){
out.push(indVars[i])
};
console.log(out[0]) /*Returns Data I Expect*/
console.log(out[1]) /*Returns Data I Don't Expect, It Should Be Showing Same as out[0]*/
divArea.InnerHTML = indVars
So the user selects the amount of indicators that should show (indicators = boxes), then they can type in the variables that go into the innerHTML...so if they select 2, the user has to fill in 2 of the user entries for each variable because the indicators will show different data. I have tried a few variations of arrays and I have gotten close but sometimes I'm getting "undefined" and then the div counts. I'm thinking the HTML Variables should be in a for loop to loop for the number of indicators but I'm not sure. Ultimately, the number of selected indicators should be 3 different entities, and within these 3 different entities can be variable data posted by the user. Thank you in advance.
for indVars, right now you're adding together divStart + userEntryVars + divEnd.
If you want indVars[0] = divStart and indVars[1] = userEntryVars, declare it like
var indVars = [divStart, userEntryVars, divEnd]
I was able to resolve this by the following code.
/*User Selection Of Indicators*/
var numInd = 3 /*This is amount of indicators that should show in innerHTML.*/
/*User Entry Variables Per Selection*/
var uHeight = 120
var uWidth = 225
/*Html Variables*/
var divStart = '<div class="col-sm-auto">'
var userEntryVars = '<img src="whatever.jpg" style="height:' + uHeight +'px; width: '+ uWidth + 'px">'
var divEnd = '</div>'
/*Div InnerHTML*/
var divArea = document.getElementById("IndicatorArea") ;
var out = []
var indVars = divStart + userEntryVars + divEnd ;
/*Loop For Number Of Indicators*/
for (i = 0; i < numInd; i++){
out.push(indVars)
};
divArea.InnerHTML = out.join("")
Related
I have a javascript function that should create a table with a dynamic number of rows and 4 columns
Could anyone please tell me why I am getting an error when running this script?
var cellText = data [row] [col]; -> where the error appears
I already looked at the array (data) individually and it is populated.
Here is my javascript and html code below:
function getHtmlTable(table){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Emails")
var Avals = ws.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
var data = ws.getRange(4, 1, (Alast-3), 4).getValues();
var rangito = ws.getRange("A4");
// Read table content
var fontColors = rangito.getFontColors();
var backgrounds = rangito.getBackgrounds();
var fontFamilies = rangito.getFontFamilies();
var fontSizes = rangito.getFontSizes();
var fontLines = rangito.getFontLines();
var fontWeights = rangito.getFontWeights();
var horizontalAlignments = rangito.getHorizontalAlignments();
var verticalAlignments = rangito.getVerticalAlignments();
var col= 1;
var row= 1;
// Build HTML Table, with inline styling for each cell
var tableFormat = 'style="border:1px solid black;border-collapse:collapse;text-align:center" border = 1 cellpadding = 5';
var html = ['<table '+tableFormat+'>'];
// Populate rows
for (row= 0;row <= Alast;row++) {
html.push('<tr style="height: 19px;">');
for (col= 0 ;col <= 4;col++) {
// Get formatted data
var cellText = data[row][col];
var style = 'style="'
+ 'font-family: ' + fontFamilies[row][col]+'; '
+ 'font-size: ' + fontSizes[row][col]+'; '
+ 'font-weight: ' + fontWeights[row][col]+'; '
+ 'background-color: ' + backgrounds[row][col]+'; '
+ 'text-align: ' + horizontalAlignments[row][col]+'; '
+ 'vertical-align: ' + verticalAlignments[row][col]+'; '
+'"';
html.push('<td ' + style + '>'
+cellText
+'</td>');
}
html.push('</tr>');
}
html.push('</table>');
return html.join('');
}
var data = ws.getRange(4, 1, (Alast-3), 4).getValues();
getRange: getRange(row, column, numRows, numColumns)
row: The starting row index of the range; row indexing starts with 1.
column: The starting column index of the range; column indexing starts with 1.
numRows: The number of rows to return.
numColumns: The number of columns to return.
So data is: getRange(row=4, column=1, numRows=X, numColumns=4) which makes data an X by 4 2D array.
If your for loop you are running through the 2D data array, and calling it, data[row][col], where call will get up to 4, because the limiting condition is col <= 4. So just remove the = sign to have col < 4 or change it to col <= 3. Do not forget, most programming languages, except MatLAB and a few selected few, have arrays start at 0, not 1, so the index is zero based, and should be called with -1 from the length.
I have a function to append table rows whenever a user selects values from checkbox popup window. If the user selects same or different check box values , the old values should be deleted. My code is not deleting/replacing the old row and somehow it deletes the name of the old row and creates extra table data values.
https://imgur.com/JjQjTaW
In this case, the second circled table row should have replaced the first circled row.
function AppendSampleTable(specimenNumberTextBoxId, specimenArray, _combinatedIdForSampleTbl) {
// var specimenNumberTextBoxId = "MOLECULAR DIAGNOSTICSSpec1";
var sampleTable = document.getElementById('ctl00_ContentPlaceHolder1_tblSample');
// var sampleTable = document.getElementById('ctl00_ContentPlaceHolder1_sampleNum6');
var specimenType = document.getElementById(specimenNumberTextBoxId).getAttribute("specimentype");
var poolSpecimenCode = document.getElementById(specimenNumberTextBoxId).getAttribute("poolspecimen");
var specimenNumber = "test";
var tableRows = $(sampleTable).find('tr');
var rowIndex = tableRows.length;
var i = 0;
var newRow;
var specimenArrayLength = specimenArray.length - 1; // Because specimenArray contains empty string for first element.
// Erase tr that has same name as requested.
var $oldRow = $(sampleTable).find('tr[name="' + _combinatedIdForSampleTbl + '"]'); //WHY IS THIS NOT WORKING OR IS IT? SHOUDL IT REMOVE OLD ROWS?// 3/28/2019
alert("old row=" + $oldRow);
$oldRow.remove();
// Append tr that contains desired values.
for (i; i < specimenArrayLength; i++) {
// If none of specimen has choosen for a pool, array will contain 'undefined', so we need to ignore that not to be appended into table.
if (specimenArray[i + 1] != undefined) {
specimenNumber = specimenArray[i + 1];
newRow = "<tr name='" + _combinatedIdForSampleTbl + "'><td class='col-xs-2'><span id='ctl00_ContentPlaceHolder1_sampleName" + (rowIndex + i + 1) + "' specimenCode='" + poolSpecimenCode + "'>POOL - " + specimenType + "</span></td><td class='col-xs-2'><span id='ctl00_ContentPlaceHolder1_sampleNum" + (rowIndex + i + 1) + "'>" + specimenNumber + "</span></td></tr>";
$(sampleTable).append(newRow);
}
}
}
I expect my code to replace the old row and not have extra empty table data values.
Any help would be appreciate. I need to create a slider based on JSON datas from the moviedb API. I created the slider showing the title, the picture and the description within a for loop but the last thing I need to achieve is to get the movie rating but instead of the number I need to show stars (half or full filled according to the datas provided).
I'm stuck and tried different things but it doesn't work. I know it's quite simple but I'm stuck.
Many thanks for any help. Do not hesitate if you need something else because it's my first post on stackoverflow.
Here is the fiddle of my work :
https://jsfiddle.net/y2hbzej8/7/
Here is my JS code to get datas :
JS :
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function (data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + '<p class="note">' + noteround + '</p>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + '</li>');
}
});
Divide the vote_average field of each row by two since values go from 0 to 10. This will give you five stars based values.
I edited your example, I added font-awesome CSS library that will give you lots and lots of icons you can play with. Check them out
Here's the edited example on JSFiddle
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function(data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
//Translate vote average field into number of stars by dividing them by two since vote_average goes from 0 to 10
var numberOfStars = Math.round(note/2);
var stars = '';
for(var index = 0; index < numberOfStars; index++)
stars += '<span class="fa fa-star"/>';
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + stars + '</li>');
}
});
});
Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]
Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.
The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data
I have a script for a sliding testimonial block, you can see it on https://www.medprodisposal.com.
The problem is the name for the testimonial is giving an undefined error vs. showing the customers name.
Here is the HTML:
<div id="container">
<h2><span>Testimonials</span></h2>
<div id="comment"></div>
</div>
<div id="test"></div>
And here is the script;
//create and fill the array
var commt = [ ];
var name = [ ];
var i = 0;
commt[0] = '<blockquote class="quote"><p>0';
commt[1] = '<blockquote class="quote"><p>1';
commt[2] = '<blockquote class="quote"><p>2';
commt[3] = '<blockquote class="quote"><p>3';
name[0] = 'Lindsey P. / Champaign, IL.</p>';
name[1] = 'Dr. San Jose / Hayward, California';
name[2] = 'Thomas H. / Palos Heights, Illinois';
name[3] = 'Mary Beth / Niceville, FL';
//shows how many comments there are
var maxComments = 4;
//get empty elements
var comment = document.getElementById('comment');
//this section will create the inital comment shown
//creates a random number
var number = Math.floor(Math.random() * 4);
//adds the HTML to div
window.onload = comment.innerHTML = "<p>" + commt[number] + "</p>" +
"<h3 class='commentSliderH3'>" + name[number] + "</h3>";
//This rotates the comments
setInterval(function () { //same content as above
var number = Math.floor(Math.random() * maxComments);
comment.innerHTML = "<p>" + commt[number] + "</p>" +
"<h3 class='commentSliderH3'>" + name[number] + "</h3>";
}, 9031); // Runs the function every 9031ms
The undefined error shows for the name. It shows correctly in IE, but not on Chrome or FF.
You have to avoid the reserved word for Javascript like name, change the variable to for example names and it works.
JSFiddle