Show contents of javascript arrays in buttons - javascript

I have the following code. How do I make the contents of the array appear on the button? The arrays have a content of 0,1,2,3,4,5. I want the the buttons which are aligned vertically to be as follows:
0
1
2
3
4
5
var family = [0, 1, 2, 3, 4, 5];
console.log(family);
for (var prop in family) {
document.getElementById('aaron-family').innerHTML += '<div class=col> <button type="button" class="list-group-item"' + prop + '</button></div>';
console.log(prop);
}
button {
width: 200px;
height: 200px;
}
<div class="container">
<div class="row">
<ul id="aaron-family">
<div class="list-group"></div>
</ul>
<div class="col">
1 of 3
</div>
<div class="col">
j 1 of 3
</div>
</div>
</div>

This is working fine now.
your code was working fine, you just forget to close the <button> tag on appending the HTML.
var family = [0, 1, 2, 3, 4, 5];
for (var prop in family) {
document.getElementById('aaron-family').innerHTML += '<div class=col> <button type="button" class="list-group-item">' + prop + '</button></div>';
}
button {
width: 200px;
height: 200px;
}
<html>
<body>
<div class="container">
<div class="row">
<ul id="aaron-family">
<div class="list-group">
</div>
</ul>
<div class="col">
1 of 3
</div>
<div class="col">j 1 of 3
</div>
</div>
</div>
</body>
</html>
I hope this was helpful to you. If there is anything else please feel free to ask.

Your loop is incorrect as well as the string html you are trying to append, you can change it to (I used string templates for better readability) :
family.forEach((value) => {
document.getElementById('aaron-family').innerHTML += `
<div class="col">
<button type="button" class="list-group-item">${value}</button>
</div>
`;
});

Related

Gallery of floated items. I want to add a class between the lines using jquery

So i will try to explain bit more into detail.
So I've got a gallery with 9 elements floated left creating 3 elements per line like this:
1 2 3 <--line 1
4 5 6 <--line 2
7 8 9 <--line 3
What i am trying to do is when i click on either element i want to add a div bellow the line its part of. For example if i click on element 2 it should add a div after the 3rd element between line 1 and 2.
I tried selecting all the 3rd elements of the line (using :nth-child) but i cant make jquery understand on which line it is.
To be honest i am really confused about how to approach this.
Any ideas would be tremendously helpful.
Thank you.
Constantin Chirila
Later edit:
The code is a mess and its part of a bigger thing so sorry for that.
<a href="#" class="dealer--item" data="hongkong">
<h4 class="dealer--item-title">Hong Kong</h4>
</a>
<a href="#" class="dealer--item" data="australia">
<h4 class="dealer--item-title">Sweden</h4>
</a>
<a href="#" class="dealer--item" data="sweden">
<h4 class="dealer--item-title">Sweden</h4>
</a>
<a href="#" class="dealer--item" data="uk">
<h4 class="dealer--item-title">United kingdom</h4>
</a>
<a href="#" class="dealer--item" data="germany">
<h4 class="dealer--item-title">Germany</h4>
</a>
<a href="#" class="dealer--item" data="netherlands">
<h4 class="dealer--item-title">The Netherlands</h4>
</a>
<a href="#" class="dealer--item" data="canada">
<h4 class="dealer--item-title">Canada</h4>
</a>
<a href="#" class="dealer--item" data="malaysia">
<h4 class="dealer--item-title">Malaysia</h4>
</a>
<a href="#" class="dealer--item" data="thailand">
<h4 class="dealer--item-title">Thailand</h4>
</a>
<a href="#" class="dealer--item" data="japan">
<h4 class="dealer--item-title">Japan</h4>
</a>
<a href="#" class="dealer--item" data="korea">
<h4 class="dealer--item-title">Korea</h4>
</a>
<a href="#" class="dealer--item" data="indonesia">
<h4 class="dealer--item-title">Indonesia</h4>
</a>
<a href="#" class="dealer--item" data="taiwan">
<h4 class="dealer--item-title">Taiwan</h4>
</a>
</div>
Jquery:
$(".dealer--item").click(function (e) {
var idSelector = $(this).attr('data');
e.preventDefault();
$('.dealer--item').not(this).removeClass('is-selected');
$(this).toggleClass("is-selected");
$(".dealer--item:nth-child(3n)").each(function (index) {
$(this).addClass("foo" + index);
});
$('foo0').after($('#' + idSelector)) //this is where i lost it as its not working for other 6 elements
$('#' + idSelector).fadeToggle(300);
});
And content that needs to be added between the lines based on the element clicked.
<div class="dealer--address" id="australia">
Address here
</div>
<div class="dealer--address" id="hongkong">
Address here
</div>
<div class="dealer--address" id="sweden">
Address here
</div>
<div class="dealer--address" id="uk">
Address here
</div>
<div class="dealer--address" id="germany">
Address here
</div>
etc...
Have you considered adding an extra div below the floated left elements and just hiding them initially with display:none; and then using jQuery to show them using the on click function.
$("#clickable element").click(function(){
$("element to show").show();
});
This is the way I do all of my click and display behaviors with jQuery.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style type="text/css">
.floating {
float: left;
width: 30%;
margin: 1%;
height: 100px;
background: #ffe4c4;
}
.Content {
display:none;
width: 100%;
background: green;
}
#contentOnDisplay {
min-height: 100px;
width: 100%;
float: left;
background: green;
display: block;
}
</style>
</head>
<body>
<div class="Content" id="floating1Content">content for 1</div>
<div class="Content" id="floating2Content">content for 2</div>
<div class="Content" id="floating3Content">content for 3</div>
<div class="Content" id="floating4Content">content for 4</div>
<div class="Content" id="floating5Content">content for 5</div>
<div class="Content" id="floating6Content">content for 6</div>
<div class="Content" id="floating7Content">content for 7</div>
<!-- <div class="Content" id="floating8Content">content for 8</div>
<div class="Content" id="floating9Content">content for 9</div>-->
<div class="floating" id="floating1"></div>
<div class="floating" id="floating2"></div>
<div class="floating" id="floating3"></div>
<div class="floating" id="floating4"></div>
<div class="floating" id="floating5"></div>
<div class="floating" id="floating6"></div>
<div class="floating" id="floating7"></div>
<!-- <div class="floating" id="floating8"></div>
<div class="floating" id="floating9"></div>-->
<script type="text/javascript">
var getLeftMostPositionOfFirstItem = $("#floating1").position().left;
$(document).ready(function() {
$(".floating").click(function() {
var elementID = $(this).attr("id");
$("#contentOnDisplay").remove(); //hides the existing contents
var firstItemOFNextRow = getTheFirstItemOfNextRow(elementID);
getAllTheConstentsOfAdivAndPrepenedIt(firstItemOFNextRow, getTheIdOfFirstItemOfNextRow(elementID));
return false;
});
});
function getTheFirstItemOfNextRow(clickedItemID) {
var getTheIdNumberOfThisItem = parseInt(clickedItemID.replace("floating", ""));
var position = $("#" + clickedItemID).position();
var idOfTheElementToBeInstertedBefore = "";
for (var i = getTheIdNumberOfThisItem + 1; i < $(".floating").length; i++) {
var leftPostitonOfThisItem = $("#floating" + i).position().left;
if (leftPostitonOfThisItem < getLeftMostPositionOfFirstItem*1.5) {
idOfTheElementToBeInstertedBefore = "#floating" + i;
break;
}
}
if (idOfTheElementToBeInstertedBefore.length == "") {
idOfTheElementToBeInstertedBefore = "#floating" + $(".floating").length;
}
return idOfTheElementToBeInstertedBefore;
};
function getTheIdOfFirstItemOfNextRow(elementID) {
return parseInt(elementID.replace("floating", ""));
};
function getAllTheConstentsOfAdivAndPrepenedIt(idToPrepend, IdNumber) {
var htmlOfTheContent = $("#floating" + IdNumber + "Content").html();
htmlOfTheContent = "<div id='contentOnDisplay'>" + htmlOfTheContent + "</div>";
if (IdNumber <= $(".floating").length - getNuumberOfItemsInLastRow()) {
$(idToPrepend).before(htmlOfTheContent);
} else {
$(idToPrepend).after(htmlOfTheContent);
}
return false;
};
function getNuumberOfItemsInLastRow() {
var numberOfColoumns = 0;
for (var i = $(".floating").length; i > 0; i--) {
var leftPostitonOfThisItem = $("#floating" + i).position().left;
numberOfColoumns++;
if (leftPostitonOfThisItem < getLeftMostPositionOfFirstItem * 1.5) {
break;
}
}
return numberOfColoumns;
};
</script>
</body>
</html>

Page keeps loading when inserting reference to jquery

I really feel this is a stupid question but I could not figure out:
Here my cshtml file, and it's rendered just fine:
#model CrashTestScheduler.Entity.Model.Channel
#{
string editFormat = string.Format("<button type='button' class='editForm' data-val-id=\"{0}\"><span class='ico-edit'></span></button>", ".Id");
const string DeleteFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('deleteChannel', { params:{ id: .Id } })\"><span class='ico-del'></span></button>";
const string EditFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('editChannel', { params:{ id: .Id } })\"><span class='ico-edit'></span></button>";
}
<script>
$(function() {
awe.popup = bootstrapPopup;
});
var getChannelGroupNameHandler = function (item) {
if (item.ChannelGroupName == null || item.ChannelGroupName=='') {
item.ChannelGroupName = $("#ChannelGroupId option:selected").text();
}
}
</script>
<div id="wrap">
<div id="page-heading">
<ol class="breadcrumb">
<li>Home</li>
<li class="active">Channels</li>
<li style="display:none;"></li>
</ol>
</div>
<div class="container">
<div class="col-md-12" id="gridRowChannels">
<div class="col-md-12">
<div class="panel panel-midnightblue-header">
<div class="panel-heading">
<h3>Channel List</h3>
<div class="options">
</div>
</div>
<div class="panel-body">
<div class="row-sub">
<button type="button" id="btnAddProject" class="btn btn-primary" onclick="awe.open('createChannel')">
Add Channel
</button>
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("createChannel").Url(Url.Action("Create", "ChannelsGrid")).Success("itemCreated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Add").Title("Add Channel")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("deleteChannel").Url(Url.Action("Delete", "ChannelsGrid")).Success("itemDeleted('ChannelsGrid')").Parameter("gridId", "ChannelsGrid").Height(200).Modal(true).Title("Delete Channel").OkText("Delete")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("editChannel").Group("Channel").Url(Url.Action("Edit", "ChannelsGrid")).Success("itemUpdated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Save").Title("Edit Channel")
</div>
<div class="row-sub">
#(Html.Awe().Grid("ChannelsGrid")
.Url(Url.Action("GetItems", "ChannelsGrid"))
.Columns(
new Column {Name = "Name", Header = "Channel Name", Sort = Sort.Asc},
new Column {Name = "ChannelGroup.Name", Header = "Channel Group", ClientFormat = ".ChannelGroupName"},
new Column {ClientFormat = DeleteFormat, Width = 50},
new Column {ClientFormat = EditFormat, Width = 50}
)
.Sortable(true)
.SingleColumnSort(true)
.LoadOnParentChange(false)
.PageSize(20)
.Groupable(false))
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12" id="pnlEditproject" style="display: none;">
</div>
</div>
</div>
But I want to use jquery to use jquery validation later on. So here I inserted them to the file.
<script src="~/Scripts/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
Now the file could not be rendered and the page keeps loading and loading. Any clues?
Looks like you already have access to jQuery library in this page since you are using...
$(function() {
awe.popup = bootstrapPopup;
});
Please remove the new references and try to view page source to find out the list of libraries that are already available.

Close a bootstrap row and start new row after every nth containing div

I have a bootstrap row which will be populated by, let's say, blog post thumbnails.
<section class="container">
<div class="row thumbs">
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
</div>
<hr class="divider" />
<div class="navigation">navigation</div>
</section
I want to close a row, insert hr tag and open a new bootstrap row after every 4th post thumbnail.
<section class="container">
<div class="row thumbs">
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
</div>
<hr class="divider" />
<div class="row">
<div class="col-sm-3">content</div>
</div>
<hr class="divider" />
<div class="navigation">navigation</div>
</section>
Is there a way to do this with jquery?
Can do something like this:
var $mainElem = $('.row'),/* adjust selector to suit page*/
$parent = $mainElem.parent(),
/* remove children after 4th from existing row */
$items = $mainElem.children(':gt(3)').detach();
if ($items.length) {
/* create new row for every 4 items removed above */
for (var i = 0; i < $items.length; i = i + 4) {
var $row = $('<div class="row">').append($items.slice(i, i + 4));
$parent.append('<hr class="divider">').append($row);
}
}
DEMO
This worked best for me:
var $d = $('.thumbs');
var $p = $('.col-sm-3:gt(3)', $d);
if ($p.length) {
$('<div class="row thumbs">').insertAfter($d).append($p);
$('<hr class="divider">').insertAfter($d);
}
Depending on your motivation to wrap each set of columns in a new row, you can style every nth row with straight CSS.
In bootstrap, if you have extra columns that spillover past 12, they just wrap into a new line anyway, so having the new row is usually redundant, although you might have some external reason to keep it in your case.
Either way, here's a CSS solution that adds a page wide horizontal divider every 4 divs:
Demo in jsFiddle & Stack Snippets
.container .row.thumbs div:nth-child(4n) {
position: static;
}
.container .row.thumbs div:nth-child(4n):after {
content: ' ';
border-top: 1px solid black;
display: block;
position: absolute;
width: 95%;
margin-left: 2.5%;
left: 0;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<section class="container">
<div class="row thumbs">
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
<div class="col-sm-3">content</div>
</div>
<div class="navigation">navigation</div>
</section>
Also, bear in mind that this won't be natively supported in < IE8

Angularjs creating a div grid from a list

I am new to AngularJS and i am trying to create the following structure:
<div class="zones">
<div class="row-fluid">
<button id="btn94" class="span4 btn">All Zones</button>
<button id="btn95" class="span4 btn">Zone 1</button>
<button id="btn96" class="span4 btn">Zone 2</button>
</div>
<div class="row-fluid">
<button id="btn97" class="span4 btn">Zone 3</button>
<button id="btn98" class="span4 btn">Zone 4</button>
<button id="btn99" class="span4 btn">Zone 5</button>
</div>
<div class="row-fluid">
<button id="btn100" class="span4 btn">Zone 6</button>
</div>
</div>
In my controller I am fetching the zones via restful web service and populating a scope object, successfully.
** Controller *
ZonesFactory.query( function(data) {
// success handler
var resultType = data.resulttype;
var objects = data.result.value;
$scope.zoneList= [];
console.log(objects);
if(resultType == "list"){
angular.forEach(objects, function (item) {
$resource(item.href).get(function(rowData) {
$scope.zoneList.push(rowData.zone);
});
});
}
}, function(error) {
// error handler
});
** In HTML **
<div class="zones">
<div class="row-fluid">
<span ng-repeat="zone in zoneList">
<button id="{{$index}}" class="span4 btn">{{zone}}</button>
<span ng-if="({{$index}}%3) == 0"> </div><div class="row-fluid"> </span >
<span>
</div>
</div>
Though, i was able to break into a new div after every three items in the list.
I am faced with the following:
1. generating a simple grid structure with div and no spans
2. how to generate the ids by incrementing an ID of say btnX (where X is a number).
Please, how can i construct the grid structure using thw div and incrementing the number part of the button ID.
You can ng-repeat over an array of numbers representing your rows, and use a nested ng-repeat coupled with ng-if to display buttons with the appropriate indexes.
<div class="zones">
<div class="row-fluid" ng-repeat="row in [0,1,2]">
<button id="btn{{94+$index}}"
ng-repeat="zone in zoneList"
ng-if="($index)/3 < row + 1 && ($index)/3 >= row" class="span4 btn">
{{zone}}
</button>
</div>
</div>
The ng-if logic could be prettier, but you get the idea.
The id of each button is created with simple interpolation. I add 94 to each $index only to match the output expected in your question. You could replace 94 with a variable initialized on your scope to ensure uniqueness.
Here is a working demo: http://plnkr.co/edit/oxdD0bRq626DbzzA54c4?p=preview
I have cracked a solution that works for me, as follows:
* IN CONTROLLER **
app.filter('partition', function($cacheFactory) {
var arrayCache = $cacheFactory('partition');
var filter = function(arr, size) {
if (!arr) { return; }
var newArr = [];
for (var i=0; i<arr.length; i+=size) {
newArr.push(arr.slice(i, i+size));
}
var cachedParts;
var arrString = JSON.stringify(arr);
cachedParts = arrayCache.get(arrString+size);
if (JSON.stringify(cachedParts) === JSON.stringify(newArr)) {
return cachedParts;
}
arrayCache.put(arrString+size, newArr);
return newArr;
};
return filter;
});
* IN HTML **
<div class="zones">
<div class="row-fluid" ng-repeat="zones in zoneList | partition:3" ng-init="outerIndex = $index">
<button id="{{'btn'+(94 + outerIndex*3+ $index)}}" class="span4 btn" ng-repeat="zone in zones">{{'btn'+(94 + outerIndex*3+ $index)}} {{zone}}</button>
</div>
</div>
Thanks for the comments, especially the fiddle. Thanks.

Protractor extract data from a repeater

Starting testing Angular JS application with protractor I would like to extract search results of my application.
To do so I need to iterate through a repeater "objects in objects" and extract the name coloumn :
I am using this code :
var result = element.all(by.repeater('object in objects').column('name'))
result.then(function(arr) {
//Traverse the repeater and extract data
for (var i = 0; i < arr.length; ++i) {
arr[i].getText().then(function(text) {
console.log( text);
console.log( arr.length);
});
}
This code displays only the first 6 elements even when my serach result is far more the 6.
Output :
TSK(AGR020J)(000)(AGR020JN00)(000)
40
40
TSK(ASA700J)(000)(ASA700JU00)(000)
40
40
TSK(AGR060J)(000)(AGR060JN00)(000)
40
40
TSK(AGT001H)(000)(AGT001HS20)(000)
40
40
TSK(ANF010J)(000)(ANF010JU00)(000)
40
40
TSK(AGT001H)(000)(AGT001HN20)(000)
40
40
40
40
....
6 is the number of elements in the first row of my results, I dont' know why the search doese not include remaining rows?
And here is the HTML temlate :
<div id="jobHolder" class="thumbJobs" style="height: 326px; overflow: hidden;" tabindex="5027">
<div id="job_1" class="job ng-scope" ng-click="showJobHoverInfo($index+1)" ng-repeat=
"object in objects" ng-class="object.jobStyle">
<div id="job_1_viewerEye" class="viewerEye" ng-click=
"viewerEye($event,$index+1, object)" ng-class="object.viewerEyeClass"></div>
<div id="job_1_jobBigPicto" class="jobBigPicto transition_2_opa">
<div id="job_1_jobsSmallPictos" class="jobsSmallPictos transition_2_opa">
<div id="job_1_jobDown" class="jobDown transition_2_opa">
<div id="job_1_jobHoverInfo" class="jobHoverInfo" ng-click=
"hideJobHoverInfo($event,$index+1)" style="left: -100%; top: 272px;"></div>
<div id="job_2" class="job ng-scope" ng-click="showJobHoverInfo($index+1)"
ng-repeat="object in objects" ng-class="object.jobStyle">
<div id="job_2_viewerEye" class="viewerEye" ng-click=
"viewerEye($event,$index+1, object)" ng-class="object.viewerEyeClass">
</div>
<div id="job_2_jobBigPicto" class="jobBigPicto transition_2_opa">
<div id="job_2_jobsSmallPictos" class="jobsSmallPictos transition_2_opa">
<div id="job_2_jobDown" class="jobDown transition_2_opa">
<div id="job_2_jobHoverInfo" class="jobHoverInfo" ng-click=
"hideJobHoverInfo($event,$index+1)" style="left: -100%; top: 272px;">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Sorry I think I have pasted the wrong HTML you can see it now after modification :
ng-repeat= "object in objects"

Categories