Dynamically add bootstrap rows using modulo - javascript

I a trying to dynamically add rows and populate them with 3 col-sm-4 using a modulo against the number of objects in a returned object from a function.
Code:
function formatSeriesCard(series) {
var card = "";
console.log(countProperties(series));
for (var i=0; i < countProperties(series); i++) {
if (i % 3 == 0 ) {
card += "<div class=\"row\">";
}
card += "<div class='col-sm-4' data-id="+i+">";
card += "<div class='action-box'>";
card += "<h4>" + '"' + series.name + '"' + "</h4>";
card += "<p>";
Instead I'm getting each row nested within the previous. Thinking I need to test for the first one and last one. Thanks.

Here is something like what you want
Bootply : http://www.bootply.com/2xnJBpyVsS
JS :
var wantedcol=14;
var mycol='<div class="col-xs-4">mycol</div>';
var startRowLabel="<div class='row'>";
var endRowLabel="</div>";
var start = "";
var end="";
var toAppend="";
for(var i=0; i<wantedcol; i++){
start="";
if(i%3==0 || i==0){
start=startRowLabel;
}
end="";
if(i!=0 && (i%3==2 || i==wantedcol-1)){
end=endRowLabel;
}
console.log(start+mycol+end);
toAppend+=start+mycol+end;
}
$('.container').append(toAppend);
HTML:
<div class="container"></div>
Comment :
You just have to take care about when you have to insert the div.row opening and closing tags

Related

print array of object in javascript and print in html tags

i am using storelocater.js for multiple location in google map and show the information according to the location with image. i can show only one image but i want to show multiple images inside the information panel. link this
Here is my code
var panelDiv = document.getElementById('panel');
storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">The nearest outlet:</li>';
var Store = storeLocator.Store;
Store.prototype.generateFieldsHTML_ = function(fields) {
var html = '';
html += '<div class="store-data">';
if(this.props_['title']){
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
}
html += '</div>';
return html;
}
var data = new storeLocator.StaticDataFeed;
data.setStores([
new storeLocator.Store('store02', new google.maps.LatLng(27.67663,85.31093), null, {images: ["img/thapathalil.jpg","img/thapathalil.jpg","img/thapathalil.jpg"]})
]);
and it shows:
Uncaught SyntaxError: Unexpected token for...
how can i solve this?? how can i fetch location inside of "images"
THANKS in advance
Actually you got Uncaught SyntaxError: Unexpected token for... because you used the for..loop in the string concatenation statement, directly after the + sign.
Change this code :
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
To the following:
html += '<div class="title"><div class="img-list clearfix">';
for (var i = 0; i <= this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
html += '<img src=' + this.props_['images'][i] + '>';
}
html += '</div></div>'
Note:
You should separate the concatenation of strings to the html
variable and the for loop logic, using html += instead of just using concatenation with + sign on multiple lines.
Make sure to wrap the properties names between two '' while accessing your objects, like in this.props_[images] where it should be this.props_['images'] and in this.props_[images[i]] where it should be this.props_['images'][i].
And the first 2 lines of your html variable decalaration and the concatenation, var html = ''; html += '<div class="store-data">'; can be shortened to just var html = '<div class="store-data">';.
I think there is a typo. Change this:
console.log(this.props_[images[i]])
to
console.log(this.props_['images'][i])
And you should use
i < this.props_['images'].length
So try this:
for (var i = 0; i < this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
}

JQuery mobile list prepend

trying to prepend my list in jquery mobile but I just can't get the divider to be on top of the most recent item added to the listview.
I've tried prepending the item that's being added but it then switches the divider to the bottom.
function loadScanItems(tx, rs) {
var rowOutput = "";
var $scanItems = $('#scanItems');
$scanItems.empty();
var bubbleCount = 0;
for (var i = 0; i < rs.rows.length; i++) {
bubbleCount = bubbleCount + 1;
//rowOutput += renderScan(rs.rows.item(i));
var row = rs.rows.item(i)
var now = row.added_on;
var date = get_date(now);
rowOutput += '<li data-icon="false"><div class="ui-grid-b"><div class="ui-block-a" style="width:50%"><h3>Su # ' + row.sunum + '</h3><p> Bin # ' + row.binnum + '</p></div><p class="ui-li-aside"><strong>' + date + '</strong></p><div class="ui-block-b" style="width:20%"></div><div class="ui-block-c" style="width:25%"><br><p>User: ' + row.userid + '</p></div></div></li>';
// rowOutput += '<li>' + row.sunum + row.binnum+ "<a href='javascript:void(0);' onclick='webdb.deleteScan(" + row.ID + ");'>Delete</a></li>";
}
$scanItems.append('<li data-role="list-divider">Scanned Items <span class="ui-li-count">' + bubbleCount + '</span></li>').listview('refresh');
$scanItems.append(rowOutput).listview('refresh');
}
The code is above with it correctly formatted with the divider on top but the list items being appended to the bottom instead of prepended to the top.
Thanks!
The problem is that your are building a string with all the scan items. That string already has an order so whether you prepend or append makes no difference. Try this simple change.
Change:
rowOutput += '<li data-icon="false">...</li>';
to:
rowOutput = '<li data-icon="false">...</li>' + rowOutput;
This will put your rowOutput string in the correct order before appending to the listview.
Here is a working DEMO

How to give ID to row dynamically?

I am generated a row dynamically in this fiddle.I want to give ID to that row .And Display that on header can we give this.I want to give ID like this 1,2,3...
But there is a problem Is that That rows are nested So can we give ID to inner row also .IF there is an row inside first his ID 1_1, 1_2....If some element is inside 1_1.then it ID id 1_1_1....So on
Can we do this ?
function buildNav(nodes) {
var result = '<div data-role="collapsible-set" id="stuff">';
var i = 0, len = nodes.length;
for(; i < len; i++) {
result += "<div data-role='collapsible' data-content-theme='c'><h3>test</h3>"+content;
if(nodes[i].testCaseList) {
result += buildNav(nodes[i].testCaseList) + "</div>";
}
result += "</div>";
}
return result + "</div>";
}
$(function(){
$('#test ').html(buildNav(testData.testCaseList)).trigger('create');
});
Try passing the value of the current level to your function and prepend it to the id.
function buildNav(nodes, level) {
var result = '<div data-role="collapsible-set" id="' + level + '">';
var i = 0, len = nodes.length;
for(; i < len; i++) {
var id = level + '_' + i;
result += "<div data-role='collapsible' data-content-theme='c'><h3>test</h3>"+content;
if(nodes[i].testCaseList) {
result += buildNav(nodes[i].testCaseList, id) + "</div>";
}
result += "</div>";
}
return result + "</div>";
}
$(function(){
$('#test ').html(buildNav(testData.testCaseList, 0)).trigger('create');
});

change the order js inserts the text into the html

I need to change the where the js inserts the text into the html currently it is always putting at the end and I need it to insert it at the start and push the others down. That is, if it inserts
<li>1</li>, <li>2</li>, <li>3</li>
it will keep it in that order I need the last one to always be listed first like
<li>3</li>, <li>2</li>, <li>1</li>
Here is the html
<div class="data">
<div class="stackleft" id="p1_stack"></div>
<div class="stackright" id="p2_stack"></div>
</div>
Here is the JavaScript
function drawStack(isFinal) {
var stackLength = Oscore[currentPlayer].stack.length;
var temp = "";
var tot = 0;
for (var i = 0; i < stackLength; i++) {
var val = Oscore[currentPlayer].stack[i];
temp += "<li>" + val + "</li>";
tot += val;
}
//if(!isFinal){
//temp = '<div class="workingScore">'+scoreTemp+'</div><br>' + temp;
//}
var writeSore = document.form1.game.value - tot;
writeit(writeSore, currentPlayer + "_score");
writeit(temp, currentPlayer + "_stack");
}
Try to loop backward:
for (var i = stackLength; i--; ) {
var val = Oscore[currentPlayer].stack[i];
temp += "<li>" + val + "</li>";
tot += val;
}
How about this:
temp = "<li>" + val + "</li>" + temp;
You were missing a quote in the code shown too (now fixed by someone's edit), probably wouldn't have worked at all as written originally.
EDIT: I think I like the loop backward approach better, but it's up to you what you think is clearest.
use prepend() from JQuery.....

JSON object with arrays converted to HTML table

the below code is the JSON response i recieve from an API. unfortunately i cannot change the way this response is sent, i can only use this response as is within the scope of Javascript/jQuery.
My goal is to transform this into a HTML table.
I have attempted to do this already myself;
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table id="res" class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index.toUpperCase() + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt" id="' + array[i]['id'] + '">' : '<tr id="' + array[i]['id'] + '">';
for (var index in array[i]) {
str += '<td style="width:15%;">' + htmlspecialchars_decode(array[i][index]) + '</td>';
}
str += '<td>Edit</td><td>Delete</td></tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
However I am only able to get the headers to show... But it works well if the JSON response has only one array ie one row returned.
the code above was adapted from several other questions like this on Stackoverflow, I have spent days on this and cannot get these results to show in a table... This is just one example of many other that are returned just like this example and i will need to reuse this solution many times making it very important to me.
"ItemArray":{
"id":"14"
,"0":
{"id":"1","username":"guest","fname":"Guest","lname":"User","email":"example#domain.com","group":"member","active":"0","url":null,"last_activity":null}
,"1":
{"id":"2","username":"system","fname":"Internal","lname":"System","email":"example#domain.com","group":"member","active":"0","url":null,"last_activity":null}
,"2":
{"id":"3","username":"master","fname":"Super","lname":"Admin","email":"example#domain.com","group":"member","active":"0","url":null,"last_activity":null}
,"3":
{"id":"14","username":"apitest","fname":"API","lname":"Test","email":"user#domain.com","group":"member","active":"0","url":null,"last_activity":"2012-10-29 02:48:43"}
}
You can't use array.length for Object, so you need:
for (var o in array) if (array.hasOwnProperty(o)) {
var row = array[o];
}
Ok... The problem is the your item array is parsed into an object. Not an array.
If you log this:
typeof array.length
The result is undefined. So your loops doesn't get run.

Categories