Loop through array in JSON - javascript

I have created a loop to cycle through the information in an API with this endpoint:
That returns data in this format (reduced in order to simplify):
{
"query": "allah",
"total_count": 3394,
"took": 153,
"current_page": 1,
"total_pages": 170,
"per_page": 20,
"results": [
{
"id": 664,
"verse_number": 171,
"chapter_id": 4,
"verse_key": "4:171",
"text_madani": "يَا أَهْلَ الْكِتَابِ لَا تَغْلُوا فِي دِينِكُمْ وَلَا تَقُولُوا عَلَى اللَّهِ إِلَّا الْحَقَّ ۚ إِنَّمَا الْمَسِيحُ عِيسَى ابْنُ مَرْيَمَ رَسُولُ اللَّهِ وَكَلِمَتُهُ أَلْقَاهَا إِلَىٰ مَرْيَمَ وَرُوحٌ مِّنْهُ ۖ فَآمِنُوا بِاللَّهِ وَرُسُلِهِ ۖ وَلَا تَقُولُوا ثَلَاثَةٌ ۚ انتَهُوا خَيْرًا لَّكُمْ ۚ إِنَّمَا اللَّهُ إِلَٰهٌ وَاحِدٌ ۖ سُبْحَانَهُ أَن يَكُونَ لَهُ وَلَدٌ ۘ لَّهُ مَا فِي السَّمَاوَاتِ وَمَا فِي الْأَرْضِ ۗ وَكَفَىٰ بِاللَّهِ وَكِيلًا",
"words": [
{
"id": 82924,
"position": 1,
"text_madani": "يَا أَهْلَ",
"text_indopak": null,
"text_simple": "يا اهل",
"verse_key": "4:171",
"class_name": "p105",
"line_number": 1,
"page_number": 105,
"code": "ﭑ",
"code_v3": "ﭑ",
"char_type": "word",
"audio": {
"url": "//verses.quran.com/wbw/004_171_001.mp3"
},
"translation": {
"id": 72752,
"language_name": "english",
"text": "O People",
"resource_name": null,
"resource_id": 59
},
"transliteration": {
"id": 72752,
"language_name": "english",
"text": "O People",
"resource_name": null,
"resource_id": 59
},
"highlight": null
}
],
"translations": [
{
"resource_name": "Abdullah Muhammad Basmeih",
"text": "dan janganlah kamu mengatakan sesuatu terhadap <em class=\"hlt1\">Allah</em> melainkan yang benar; sesungguhnya Al Masih Isa",
"id": 217603,
"language_name": "malay",
"resource_id": 39
}
]
}
]
}
It goes through the array of results and displays each one in an <li> tag. Then it goes through the translations. The following snippet displays only the first element of array, I want to include a new list inside my list item (right after the verse key) with all the translations inside more <li> tags. Is there any way to do this?
The snippet:
$.getJSON(url, function (data) {
count = data.total_count;
took = data.took;
results = data.results;
var li = '';
results = data.results;
var li = '';
for (const x of results) {
li +=
'<li>' +
x.text_madani +
'<br><span class="surah">' +
x.translations[0].text +' - '+ x.translations[0].resource_name+
'</span><br> <span class="surah">' +
x.verse_key +
'</span><br></li>';
}
document.getElementById('demo').innerHTML = li;
document.getElementById('Results').innerHTML =
'Results: ' + count + '';
document.getElementById('Time').innerHTML =
'Took: ' + took + ' milliseconds to load ' + count + ' results';
})
here's all the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<script
type="text/javascript"
src="https://code.jquery.com/jquery-2.1.1.min.js"
></script>
<link
href="https://fonts.googleapis.com/css?family=Google+Sans+Display:wght#300;400;700;800;900&display=swap"
rel="stylesheet"
/>
</head>
<body>
<style>
body {
font-family: 'Google Sans Display', sans-serif;
}
em{
font-weight:900;
font-style: normal;
}
li {
font-size: 20px;
margin-bottom: 4vh;
font-weight: 400;
}
.content {
margin-left: 20vw;
margin-right: 20vw;
text-align: justify;
}
:root {
--primary: #23adad;
--greyLight: #23adade1;
--greyLight-2: #cbe0dd;
--greyDark: #2d4848;
}
ul {
list-style-type: none;
}
.items-list {
max-width: 90vw;
margin: 2rem;
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-gap: 3rem;
justify-content: center;
align-content: center;
}
#media only screen and (max-width: 600px) {
.items-list {
grid-template-columns: repeat(2, 1fr);
}
}
.item {
width: 10rem;
height: 10rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: var(--greyDark);
cursor: pointer;
}
.item span {
background: #ffffff;
box-shadow: 0 0.8rem 2rem rgba(90, 97, 129, 0.05);
border-radius: 0.6rem;
padding: 2rem;
font-size: 3rem;
transition: all 0.3s ease;
}
.item:hover span {
transform: scale(1.2);
color: var(--primary);
}
.item p {
font-size: 1.2rem;
margin-top: 1rem;
color: var(--greyLight);
}
.page {
display: flex;
justify-content: center;
align-items: center;
height: 5rem;
margin: 3rem;
border-radius: 0.6rem;
background: #ffffff;
box-shadow: 0 0.8rem 2rem rgba(90, 97, 129, 0.05);
}
.page__numbers, .page__btn, .page__dots {
display: flex;
justify-content: center;
align-items: center;
margin: 0.8rem;
font-size: 1.4rem;
cursor: pointer;
}
.page__dots {
width: 2.6rem;
height: 2.6rem;
color: var(--greyLight);
cursor: initial;
}
.page__numbers {
width: 2.6rem;
height: 2.6rem;
border-radius: 0.4rem;
}
.page__numbers:hover {
color: var(--primary);
}
.page__numbers.active {
color: #ffffff;
background: var(--primary);
font-weight: 600;
border: 1px solid var(--primary);
}
.page__btn {
color: var(--greyLight);
pointer-events: none;
}
.page__btn.active {
color: var(--greyDark);
pointer-events: initial;
}
.page__btn.active:hover {
color: var(--primary);
}
</style>
<div class="content">
<h3 id="Results"></h3>
<h3 id="Time"></h3>
<h6 id="demo"></h6>
</div>
<div id="app" class="container">
<ul class="page">
<li class="page__btn"><span class="material-icons">chevron_left</span></li>
<li class="page__numbers"> 1</li>
<li class="page__numbers active">2</li>
<li class="page__numbers">3</li>
<li class="page__numbers">4</li>
<li class="page__numbers">5</li>
<li class="page__numbers">6</li>
<li class="page__dots">...</li>
<li class="page__numbers"> 10</li>
<li class="page__btn"><span class="material-icons">chevron_right</span></li>
</ul>
</div>
<script>
window.onload = function () {
var search = prompt('search');
var arText;
var enText;
var surah;
var ayahNumber;
var surahAndAyah;
$(document).ready(function () {
getQuote();
$('#shuffle').on('click', getQuote);
$('#tweet').click(function () {
var tweetLink = '' + '"' + enText + '" QS' + surahAndAyah;
window.open(tweetLink);
});
});
function getQuote() {
var ayah = Math.floor(Math.random() * 6236) + 1;
var url =
'http://api.quran.com:3000/api/v3/search?q= ' +
search +
' &size=20&page=0&language=en';
arText;
enText;
surah;
ayahNumber;
surahAndAyah;
$.getJSON(url, function (data) {
count = data.total_count;
took = data.took;
results = data.results;
var li = '';
results = data.results;
var li = '';
for (const x of results) {
li +=
'<li>' +
x.text_madani +
'<br><span class="surah">' +
x.translations[0].text +' - '+ x.translations[0].resource_name+
'</span><br> <span class="surah">' +
x.verse_key +
'</span><br></li>';
}
document.getElementById('demo').innerHTML = li;
document.getElementById('Results').innerHTML =
'Results: ' + count + '';
document.getElementById('Time').innerHTML =
'Took: ' + took + ' milliseconds to load ' + count + ' results';
})
.done(function () {
console.log('second success');
})
.fail(function (jqXHR, textStatus, errorThrown) {
//alert("You're offline! " + textStatus);
})
.always(function () {
console.log('complete');
});
}
};
</script>
</body>
</html>

You can achieve that by looping through both the results and translations keys, something like this:
$.getJSON(url, function (data) {
count = data.total_count;
took = data.took;
results = data.results;
var li = '';
results = data.results;
for (const x of results) {
li += '<li>' + x.text_madani + '<br>' +
'<span class="surah">' + x.verse_key + '</span><ul>'
for (const y of x.translations) {
li += '<li><span class="surah">' +
y.text +' - '+ y.resource_name+
'</span></li>';
}
li += '</ul></li>';
}
document.getElementById('demo').innerHTML = li;
document.getElementById('Results').innerHTML =
'Results: ' + count + '';
document.getElementById('Time').innerHTML =
'Took: ' + took + ' milliseconds to load ' + count + ' results';
})
Please keep in mind that this might mess with your HTML if your data is not sanitized or if it's not using some kind of abstraction to generate the HTML.
Creating HTML using a string concatenated from results from a API is not encouraged.

you can create a new ul element and use insertAdjacentHTML('beforeend', str) in order to append the text as HTML element.
function printTranslations(translations) {
var ul = '<ul>';
for (const text of translations) {
ul +=
'<li><span class="surah">' +
text.text + ' - ' + text.resource_name +
'</span></li>';
}
return ul + '</ul>';
}
function (data) {
count = data.total_count;
took = data.took;
results = data.results;
var ul = document.createElement('ul');
results = data.results;
for (const x of results) {
ul.insertAdjacentHTML('beforeend',
'<li>' +
x.text_madani +
'<br><span class="surah">' +
printTranslations(x.translations) +
'<span class="surah">' +
x.verse_key +
'</span><br></li>');
}
document.getElementById('demo').appendChild(ul);
document.getElementById('Results').innerHTML = 'Results: ' + count + '';
document.getElementById('Time').innerHTML =
'Took: ' + took + ' milliseconds to load ' + count + ' results';
}

Related

How to get results of json using search input to group sub objects into one result?

I have this jQuery code that gets the data on data.json file and outputs the result on search box. I'm having trouble into it because when I search the data it outputs like this:
Ken
[projects details here]
Ken
[projects details here]
What I want to achieve is to group the search result like this:
Ken
[projects details here]
[projects details here]
I guess its probably on my second loop, but how can I alternate the code to get the result that I want?
Here's the full code though:
data.json
{
"user": [
{
"name": "Ken",
"projects": [
{
"image": "./resources/assets/avatars/uniswap-1.png",
"title": "TestKen1",
"text_sub": "(USD)",
"text_price": "(USD)"
},
{
"image": "./resources/assets/avatars/uniswap-2.png",
"title": "TestKen2",
"text_sub": "(USD)",
"text_price": "(USD)"
}
]
},
{
"name": "Vodka",
"projects": [
{
"image": "./resources/assets/avatars/uniswap-3.png",
"title": "TestVodka1",
"text_sub": "(USD)",
"text_price": "(USD)"
},
{
"image": "./resources/assets/avatars/uniswap-4.png",
"title": "TestVodka2",
"text_sub": "(USD)",
"text_price": "(USD)"
}
]
}
]
}
HTML
<style>
#result {
position: absolute;
width: 100%;
max-width: 870px;
cursor: pointer;
overflow-y: auto;
max-height: 400px;
box-sizing: border-box;
z-index: 1001;
background: #FFFFFF;
box-sizing: border-box;
box-shadow: 0px 25px 45px rgba(18, 16, 50, 0.2);
border-radius: 12px;
}
.list-group {
margin-top: 10px;
border: 0;
}
.link-class:hover {
background-color: #f1f1f1;
}
.list-group-item {
border-bottom: 0;
padding-bottom: 12px;
}
.list-group-item-inline {
display: flex;
flex-wrap: wrap;
}
</style>
<br /><br />
<div class="container" style="width:900px;background:#000;padding:20px;">
<div class="header-search lg-hidden">
<input type="text" name="search" placeholder="Search" id="search">
<ul class="list-group" id="result"></ul>
</div>
<br />
</div>
script
<script>
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$('#search').keyup(function () {
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('data.json', function (data) {
$.each(data, function (key, value) {
for (var i = 0; i < value.length; ++i) {
for (var j = 0; j < value.length; ++j) {
if (value[i].name.search(expression) != -1) {
$('#result').append(
'<li class="list-group-item link-class">' +
'<h6 class="fw-400 mb-8">' + value[i].name + '</h6>' +
'<div class="list-group-item-inline">' +
'<img class="mr-6 w-24" src="' + value[i].projects[j].image + '">' +
'<p><b>' + value[i].projects[j].title + '</b> ' + value[i].projects[j].text_sub + '<span class="ml-8">' + value[i].projects[j].text_price + '</p>' +
'</div>' +
'</div>' +
'</li>'
);
}
}
}
});
});
});
$('#result').on('click', 'li', function () {
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
});
});
</script>

How can I pull in specific number of elements from a JQuery function?

I have a JS function that pulls in all the data based on search results. However, I want to now limit it to the top 6 listings. What is the quickest way to do that? I'm drawing complete blanks on it.
jQuery(document).ready(function ($) {
// Your code here
var $properties = $(".properties");
myvr.properties().then(function (data) {
console.log(data);
data.results.forEach(function (property) {
console.log(property.name);
$properties.append(
'<div class="col-12 col-md-6 col-lg-4">'+
'<div class="min-height-smaller" style="background:url(' +
property.photo.url +
'); background-size:cover; background-position:center;"></div>' +
'<p class="sub-heading">' +
property.name +
"</p>" +
property.headline +
"<br><br>" +
' <a class="primary-btn booking-link" data-property-id="' +
property.key +
'" href="/property/?p=' +
property.slug+"&key="+property.key +
'">Pricing and Details</a> <br><br></div>'
);
});
});
});
You can use index to keep counter and add a condition if(index < 6) it will check if index value is less then 6 then only append values to div properties .
Demo Code :
//demo json datas
var data = {
"results": [{
"name": "something"
}, {
"name": "something1"
}, {
"name": "something3"
}, {
"name": "something4"
}, {
"name": "something5"
}, {
"name": "something6"
}, {
"name": "something7"
}, {
"name": "something8"
}]
}
jQuery(document).ready(function($) {
var $properties = $(".properties");
//add index
data.results.forEach(function(property, index) {
//only append top 6 values
if (index < 6) {
$properties.append(
"<p class='sub-heading'>" +
property.name +
"</p>"
);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="properties"></div>
you can use JQuery.slice():
var $properties = $(".properties").slice(0,6);
$properties.addClass("red");
.red{
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="properties">1</div>
<div class="properties">2</div>
<div class="properties">3</div>
<div class="properties">4</div>
<div class="properties">5</div>
<div class="properties">6</div>
<div class="properties">7</div>
<div class="properties">8</div>
<div class="properties">9</div>
<div class="properties">10</div>
You can do something like this:
const teams = document.querySelectorAll('.standings ol li');
teams.forEach((team, idx) => {
if(idx < 4) {
team.classList.add('champions-league');
}
if(idx == 4) {
team.classList.add('europa-league');
}
const relegationIdxs = Array.from({length: 3}, (_, i) => (teams.length - 1) - i);
if(relegationIdxs.includes(idx)) {
team.classList.add('relegation');
}
});
.standings {
--champions-league: #4285F4;
--europa-league: #FA7B17;
--relegation: #EA4335;
background: #F8F9FA;
padding: 10px;
margin: 5px;
border-radius: 5px;
border: solid 1px #EBEBEB;
}
.champions-league {
color: var(--champions-league);
}
.europa-league {
color: var(--europa-league);
}
.relegation {
color: var(--relegation);
}
.legend span {
display: block;
margin: 1px 3px 0px 0px;
font-size: 14px;
}
span:before {
content: "■";
display: inline-block;
width: 15px;
height: 15px;
margin-right: 5px;
}
span[status="champions-league"]:before {
color: var(--champions-league)
}
span[status="europa-league"]:before {
color: var(--europa-league)
}
span[status="relegation"]:before {
color: var(--relegation)
}
<div class="standings">
<div class="legend">
<span status="champions-league">UEFA Champions League</span>
<span status="europa-league">Europa League</span>
<span status="relegation">Relegation</span>
</div>
<ol>
<li>Real Madrid</li>
<li>Barcelona</li>
<li>Atletico Madrid</li>
<li>Valencia</li>
<li>Real Sociedad</li>
<li>Getafe</li>
<li>Sevilla</li>
<li>Levante</li>
<li>Eibar</li>
<li>Elche</li>
<li>Osasuna</li>
</ol>
</div>

Move Array value to another specific array

Hi i have this code below that consists of 2 list Total fruits and random fruits for my current codes i'm able to click on the values of Random fruits and send that array value to the green fruits array and vice versa. What im trying to accomplish is to use my fruits array key value [type] to map where the value in random fruit array should go. is there any easy way to accomplish this? Any help would be greatly appreciated!
var red = {};
var green = {};
var random = {};
var fruits = [];
var fruits1 = {["fruit"]:"Apple", ["type"]:"1"}
var fruits2 = {["fruit"]:"Tomato", ["type"]:"1"}
var fruits3 = {["fruit"]:"Lime", ["type"]:"2"}
var fruits4 = {["fruit"]:"Guava", ["type"]:"2"}
fruits.push(fruits1,fruits2,fruits3,fruits4);
var randomFruits = fruits.filter(x => x.fruit).map(x => x.fruit);
var key = "Red Fruits";
red[key] = ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'];
var key2 = "Green Fruits";
green[key2] = ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'];
var key3 = "Random Fruits";
random[key3] = randomFruits;
function redraw() {
var combineString = '';
$.each(red[key], function(index) {
combineString += ('<div class="pilldiv redpill class">' + red[key][index] + '</div>');
});
$('.combineclass').html(combineString);
$.each(green[key2], function(index) {
combineString += ('<div class="pilldiv greenpill class">' + green[key2][index] + '</div>');
});
$('.combineclass').html(combineString);
var randomString = '';
$.each(random[key3], function(index) {
randomString += ('<div class="pilldiv randompill class">' + random[key3][index] + '</div>');
});
$('.randomclass').html(randomString);
}
function listener() {
$(document).ready(function() {
$(document).on("click", "#randomid div", function() {
data = this.innerHTML;
k1 = Object.keys(random).find(k => random[k].indexOf(data) >= 0)
index = random[k1].indexOf(data);
random[k1].splice(index, 1);
green[key2].push(data);
$(".total_count_Green_Fruits").html(key2 + ': ' + green[key2].length);
var element = $(this).detach();
$('#combineid').prepend('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
});
});
$('body').on('click', 'div.new-green-fruit', function() {
data2 = this.innerHTML;
k2 = Object.keys(green).find(k => green[k].indexOf(data2) >= 0)
index2 = green[k2].indexOf(data2);
green[k2].splice(index2, 1);
random[key3].push(data2);
$(this).detach();
var element2 = $(this).detach();
$('#randomid').prepend('<div class="pilldiv randompill class" >' + element2.html() + '</div>');
});
}
redraw();
listener();
.pilldiv {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
color: Black;
margin: 2px;
}
.randompill:after{
content: "\002B";
float: left;
width:16px;
}
.new-green-fruit:after{
content: "\292B";
float: left;
width:16px;
}
.redpill {
background-color: Pink;
cursor:default;
}
.greenpill {
background-color: SpringGreen;
cursor:default;
}
.randompill {
background-color: LightBlue;
cursor:pointer;
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center;
}
.wrappingflexbox {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.top {
margin-bottom: 20px
}
h3{
font-weight: normal;
}
.panel {
display: table;
height: 100%;
width: 60%;
background-color:white;
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}
.new-green-fruit{
background-color: LightBlue;
cursor:pointer;
}
.top{
margin-bottom:30px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div class="panel">
<div style="float:left;width:calc(50% - 5px);">
<h3 class="class center">Total Fruits</h3>
<div id="combineid" class="combineclass wrappingflexbox top"></div>
</div>
<div style="float:right;width:calc(50% - 5px)">
<h3 class="class center">Random Fruits</h3>
<div id="randomid" class="randomclass wrappingflexbox top"></div>
</div>
</div>
</body>
</html>
You should apply some check like
if type == 1
prepend
else if type == 2
append
Just update your function as below
$(document).ready(function() {
$(document).on("click", "#randomid div", function() {
data = this.innerHTML;
k1 = Object.keys(random).find(k => random[k].indexOf(data) >= 0)
index = random[k1].indexOf(data);
random[k1].splice(index, 1);
let fromrandom = fruits.find(k => k.fruit == data);
if(fromrandom.type == 1) {
green[key2].push(data);
$(".total_count_Green_Fruits").html(key2 + ': ' + green[key2].length);
var element = $(this).detach();
$('#combineid').prepend('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
}
else if(fromrandom.type == 2) {
red[key].push(data);
$(".total_count_Red_Fruits").html(key + ': ' + red[key].length);
var element = $(this).detach();
$('#combineid').append('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
}
console.log(JSON.stringify(red)+" "+ JSON.stringify(green)+" "+JSON.stringify(fromrandom));
});
});

How to implement a jQuery plugin in my server?

I'm new to jQuery and web development. I have succesfully implemented other jQuery plugins like data tables or a simple sliders.
I'm having some problems when trying to make this run:
http://jsfiddle.net/KurtWM/pQnPg/
I know that is a must to initialize my code so I did the following:
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#survey1').numericScale();
} );
</script>
I copied the js part exactly as it is from the provided link and uploaded to my server with the name:
jquery.numericScale.js
I have included jQuery and this plugin in the following way:
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" src="media/js/jquery.numericScale.js"></script>
Regarding the HTML part I just copied it into my HTML body.
I really don't have a clue of what could I be doing wrong.
Try removing this from the end of your jquery.numericScale.js file:
var disciplines = $('#survey1').numericScale({
'responseRange' : 5,
'lowOpinionAnswer' : 'Least like me',
'highOpinionAnswer' : 'Most like me'
});
console.dir(disciplines);
Add this to your html page after your loaded plugins:
<script>
$('#survey1').numericScale({
'responseRange' : 5,
'lowOpinionAnswer' : 'Least like me',
'highOpinionAnswer' : 'Most like me'
});
</script>
This should work for you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.survey-wrapper
{
position: relative;
display: table;
width: 100%; /*height: 500px;*/
max-width: 640px;
border-collapse: separate !important;
border-spacing: 1px !important;
}
ol.survey
{
list-style: decimal; /*margin-top: 160px;*/
list-style-position: inside;
}
ol.survey > li:last-child
{
border-bottom: 1px solid #CDCDCD;
}
ol.survey li
{
padding-left: -20px;
border-top: 1px solid #CDCDCD;
border-right: 1px solid #CDCDCD;
border-left: 1px solid #CDCDCD;
}
ol.survey li.alt, ol.survey li:nth-child(even)
{
background-color: #E8E8E4;
}
.scores > div
{
background: #E8E8E4;
}
.scores div.alt, .scores > div:nth-child(even)
{
background-color: #E8E8E4;
}
ol.survey li .opinion-question
{
margin-bottom: 0.5em;
font-weight: bold;
}
ol.survey li
{
padding-top: 6px;
padding-bottom: 1px;
padding-left: 12px;
}
ol.survey li .opinion-responses
{
display: table;
width: 100%;
margin-bottom: 1.0em;
}
ol.survey li .opinion-responses .bipolar-adjective
{
display: table-cell;
width: 25%;
text-align: center;
vertical-align: middle;
font-style: italic;
}
ol.survey li .opinion-responses .response-choice
{
display: table-cell;
width: 10px;
text-align: center;
vertical-align: middle;
}
ol.survey li .opinion-responses .response-choice input[type=radio], ol.survey li .opinion-responses .response-choice input.radio
{
}
.scores
{
width: 100%;
height: 400px;
position: relative;
}
.scores .discipline
{
display: block;
position: absolute;
bottom: 0;
text-align: center;
background: #E8E8E4 url(../images/gifts_orange.png) no-repeat 0 0;
border: 1px solid #FFFFFF;
}
.scores .discipline .discipline-name
{
text-align: center;
position: relative;
bottom: 24px;
z-index: 200;
font-family: "Futura Lt BT" , helvetica, sans-serif;
}
.scores .discipline .discipline-total
{
text-align: center;
display: block;
font-weight: bold;
font-size: 150%;
font-family: "Futura Md BT" , helvetica, sans-serif;
margin-top: 0px;
}
.scores .selected
{
background: #1047a9 url(../images/gifts_blue.png) no-repeat 0 0 !important;
}
.scores .selected .discipline-total
{
color: #FFFFFF !important;
}
.box
{
position: relative;
width: 60%;
background: #ddd;
-moz-border-radius: 4px;
border-radius: 4px;
padding: 2em 1.5em;
color: rgba(0,0,0, .8);
text-shadow: 0 1px 0 #fff;
line-height: 1.5;
margin: 60px auto;
}
.box:before, .box:after
{
z-index: -1;
position: absolute;
content: "";
bottom: 15px;
left: 10px;
width: 50%;
top: 80%;
max-width:300px;
background: rgba(0, 0, 0, 0.7);
-webkit-box-shadow: 0 15px 10px rgba(0,0,0, 0.7);
-moz-box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7);
box-shadow: 0 15px 10px rgba(0, 0, 0, 0.7);
-webkit-transform: rotate(-3deg);
-moz-transform: rotate(-3deg);
-o-transform: rotate(-3deg);
-ms-transform: rotate(-3deg);
transform: rotate(-3deg);
}
.box:after
{
-webkit-transform: rotate(3deg);
-moz-transform: rotate(3deg);
-o-transform: rotate(3deg);
-ms-transform: rotate(3deg);
transform: rotate(3deg);
right: 10px;
left: auto;
}
.rotate
{
/* Safari */
-webkit-transform: rotate(-90deg); /* Firefox */
-moz-transform: rotate(-90deg); /* IE -ms-transform: rotate(-90deg); */ /* Opera */
-o-transform: rotate(-90deg);
}
</style>
</head>
<body>
<form>
<ol id="survey1" class="survey">
<li class="question" title="Prophecy">When a situation needs to be corrected I feel a burden to speak up about it in order to correct it.</li>
<li class="question" title="Shepherd">I feel a special concern for less mature Christians and feel compelled to care for them spiritually.</li>
<li class="question" title="Teaching">I find it easy and enjoyable to spend time in intensive Bible study.</li>
<li class="question" title="Encouraging">I am able to help others identify problems and offer solutions.</li>
<li class="question" title="Giving">I don't understand why others don't give as much and as freely as I do.</li>
<li class="question" title="Mercy">I am comfortable visiting people who are sick and disabled.</li>
<li class="question" title="Evangelism">I have greater desire than most to witness to non-Christians.</li>
<li class="question" title="Administration">If there is no leadership in a group I will step up and take charge.</li>
<li class="question" title="Serving">I enjoy being called upon to do special jobs around the church.</li>
<li class="question" title="Prophecy">When issues are being dealt with in a group, I speak up rather than just listening.</li>
<li class="question" title="Shepherd">I find myself especially concerned that newer Christians will be influenced by false teachers and be harmed in their spiritual growth as a result. </li>
<li class="question" title="Teaching">Others sometimes accuse me of being too technical or detail-oriented. </li>
<li class="question" title="Encouraging">I would rather talk personally with someone rather than refer them elsewhere. </li>
<li class="question" title="Giving">I find myself looking for opportunities to give my money without being asked to give. </li>
<li class="question" title="Mercy">I have a tendency to think about things for a while before making a decision. </li>
<li class="question" title="Evangelism">Witnessing to non-Christians comes easily to me. </li>
<li class="question" title="Administration">I enjoy handling the details of organizing ideas, people, resources, and time in order to have more effective ministry. </li>
<li class="question" title="Serving">I feel that I am not specifically skilled, but I enjoy doing what needs to be done around the church. </li>
</ol>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function( $ ) {
$.fn.extend({
numericScale: function(options) {
var defaults = {
responseRange: 5,
topNumber: 3,
lowOpinionAnswer: 'Lowest',
highOpinionAnswer: 'Highest'
};
var scores = []; // Array to hold scores
var key; // HTML5 localStorage key
var disciplines = []; // Array to hold disciplines
var aHighVals = []; // Array to hold n highest scores
var options = $.extend(defaults, options);
// Act on every target list of the plugin.
return this.each(function() {
var $list = $(this);
key = $list.attr('id') + "_key";
// Replace list items with survey controls.
$($list).children().each(function(index) {
createQuestion($list, $(this), index);
}).filter(':odd').addClass('alt');
// Create HTML for survey & scores containers and button
$list.wrap('<div id="wrap-' + $list.attr('id') +
'" class="survey-wrapper"></div>');
$list.after('<div id="scores-' + $list.attr('id') +
'" class="scores"></div>');
$list.after('<input type="button" id="submitBtn"' +
' class="button btnStyle" value="Show My Gifts"' +
' disabled="disabled" />');
// Hide scores initially
$('#scores-' + $list.attr('id')).hide();
loadScores();
setSubmitBtnState();
console.dir(scores);
// ====================
// Handler:
// ====================
$('input[type="radio"]').change(function(e) {
// Get the discipline of the question
var discipline = $(e.target).closest('li[class~="question"]').attr('data-discipline');
var qNum = $(e.target).attr('name').substr(1) - 1;
// Replace the question's object property 'value' in the Scores array with the new selection
scores[qNum].value = $(e.target).val();
storeScores();
setSubmitBtnState();
});
// ====================
// Function:
// ====================
function storeScores() {
var jsonScores = JSON.stringify(scores);
localStorage.setItem(key, jsonScores);
}
// ====================
// Function:
// ====================
function setSubmitBtnState() {
if (getFormFinished()) {
$('#submitBtn').removeAttr('disabled');
}
else {
$('#submitBtn').attr('disabled', 'disabled');
}
}
// ====================
// Function:
// ====================
function getFormFinished() {
//var boolFinished = true;
for (var i = 0; i < scores.length; i++) {
if (scores[i].value == 0) {
//boolFinished = false;
return false;
break;
}
}
//return boolFinished;
return true;
}
// ====================
// Function:
// ====================
function createQuestion(oList, oItem, index) {
// Add the 'title' of the list item
var title = oItem.attr('title');
var qName = "q" + (index + 1);
// Create score items in scores Array.
createScore(oItem, title, qName);
var question = "<div class='opinion-question'>" +
oItem.text() + "</div>" +
"<div class='opinion-responses'>" +
"<span class='bipolar-adjective'>" +
defaults.lowOpinionAnswer + "</span>";
// Create a radio button group for each question.
for (var i = 1; i <= defaults.responseRange; ++i) {
question += "<span class='response-choice'>" +
"<input type='radio' name='" + qName +
"' value='" + i + "' class='radio'";
// Create a LocalStorage item for each question.
//check if discipline's localstorage is set.
if (localStorage.getItem(oList.attr('id') + "_" + qName)) {
if (localStorage.getItem(oList.attr('id') + "_" + qName) == i) {
question += " checked='checked'";
}
}
// Add required attribute to first radio button in group to allow validation with the jquery.validate.js plugin.
if (i == 1) {
question += " validate='required:true'";
}
question += " />" + i + "</span>";
}
question += "<span class='bipolar-adjective'>" + defaults.highOpinionAnswer + "</span>" + "</div>";
oItem.empty().prepend(question).attr('data-discipline', oItem.attr('title')).removeAttr('title');
}
// ====================
// Function:
// ====================
function createScore(oItem, d, qName) {
var score = {};
score.question = qName;
score.value = oItem.val();
score.discipline = d;
scores.push(score);
}
// ====================
// Function:
// ====================
function addScoreToPage(score) {
if (replace(scores, score.question, score.value)) {
var scoreUl = document.getElementById('scores-' + $list.attr('id') + '-ul');
var li = document.createElement('li');
li.innerHTML = score.question + '; ' + score.value + '; ' + score.discipline;
if (scoreUl.childElementCount > 0) {
scoreUl.insertBefore(li, scoreUl.firstChild);
} else {
scoreUl.appendChild(li);
}
}
}
// ====================
// Function:
// ====================
function replace(arrayName, replaceTo, replaceWith) {
for (var i = 0; i < arrayName.length; i++) {
if (arrayName[i].question == replaceTo) {
arrayName.splice(i, 1, replaceWith);
return true;
} else {
return false;
}
}
}
// ====================
// Function:
// ====================
function getHighestScores(oItems, num) {
for (var key in oItems) {
var obj = oItems[key];
for (var prop in obj) {
}
}
}
// ====================
// Function:
// ====================
function surveySetup() {
var submitButton = document.getElementById("submitBtn");
submitButton.onclick = submitSurvey;
if (!window.localStorage) {
alert("The Web Storage API is not supported in your browser. You may still submit the form, but your answers will not be saved to your browser.")
} else {
loadScores();
}
}
// ====================
// Handler:
// ====================
$("#submitBtn").click(function() {
if (!window.localStorage) {
alert("The Web Storage API is not supported in your browser. You may still submit the form, but your answers will not be saved to your browser.")
} else {
submitSurvey();
$('html, body').animate({
scrollTop: $("html, body").offset().top
}, 1000);
}
});
// ====================
// Function:
// ====================
function submitSurvey() {
// Create visual elements for scores.
var surveyId = 'div#scores-' + $list.attr('id');
var dNumber = 0;
var dWidth;
var maxHeight = 350;
var tallBarHeight = 0;
$(surveyId).empty();
for (var i = 0; i < scores.length; i++) {
if ($('div#' + scores[i].discipline).length == 0) {
var dScore = tallyDiscipline(scores[i].discipline);
dNumber++;
var discipline = {};
discipline.name = scores[i].discipline;
discipline.value = dScore;
disciplines.push(discipline);
$(surveyId).append("<div id='" + scores[i].discipline + "' class='discipline'><div class='discipline-name'>" + scores[i].discipline + "</div><div class='discipline-total'>" + dScore + "</div>" + "</div>");
if (dScore > tallBarHeight) {
tallBarHeight = dScore;
}
};
$(surveyId).show('fast');
};
//console.dir(disciplines);
//return(disciplines);
dWidth = 100 / dNumber
for (var ii = 0; ii < dNumber; ii++) {
$('.scores .discipline').eq(ii).css({
'left': Math.floor(dWidth) * ii + '%'
});
$('.scores .discipline').eq(ii).css({
'width': (Math.floor(dWidth) - 1) + '%'
});
barHeight = Math.floor((disciplines[ii].value / tallBarHeight) * maxHeight)
$('.scores .discipline').eq(ii).animate({
height: barHeight
}, 2000);
$('.scores .discipline'); //.addClass('box');
};
getHighestValues();
$list.hide();
$('#submitBtn').hide();
$('[id*="btnSaveGifts"]').show();
};
// ====================
// Function:
// ====================
function getHighestValues() {
for (var i = 0; i < disciplines.length; i++) {
aHighVals[i] = [disciplines[i].value, disciplines[i].name];
}
aHighVals.sort(mySorting);
aHighVals.splice(defaults.topNumber, aHighVals.length - defaults.topNumber);
for (var ii = 0; ii < aHighVals.length; ii++) {
$('#' + aHighVals[ii][1]).addClass('selected');
$('input[id*="hdnSelectedVals"]').val($('input[id*="hdnSelectedVals"]').val() + aHighVals[ii][1]);
if (aHighVals.length - 1 > ii) {
$('input[id*="hdnSelectedVals"]').val($('input[id*="hdnSelectedVals"]').val() + ", ");
}
}
}
// ====================
// Function:
// ====================
function mySorting(a, b) {
a = a[0];
b = b[0];
return b == a ? 0 : (b < a ? -1 : 1)
}
// ====================
// Function:
// ====================
function tallyDiscipline(discipline) {
var total = 0;
for (var i = 0; i < scores.length; i++) {
if (scores[i].discipline == discipline) {
total += parseInt(scores[i].value);
}
}
return total;
}
// ====================
// Function:
// ====================
function loadScores() {
var jsonScores = localStorage.getItem(key);
if (jsonScores != null) {
scores = JSON.parse(jsonScores);
for (var i = 0; i < scores.length; i++) {
addScoresToPage(scores[i]);
}
}
}
// ====================
// Function:
// ====================
function addScoresToPage(score) {
$('input:radio[name=' + score.question + '][value=' + score.value + ']').attr('checked', 'checked');
}
});
}
});
})( jQuery );
var disciplines = $('#survey1').numericScale({
'responseRange' : 5,
'lowOpinionAnswer' : 'Least like me',
'highOpinionAnswer' : 'Most like me'
});
console.dir(disciplines);
</script>
</body>
</html>
I've put everything is one file

How do i center absolute list items in a unordered list?

I am trying to build a seat reservation system using links and unordered list items. The rows in the floor plan differ from each other. Row 1 has 22 seats, row 2 has 24 seats etc. I'm trying to center the list items but i cant figure it out.
Here is my code:
$(function generateSeats() {
var settings = {
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 22,
seatHeight: 22,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function(reservedSeat) {
var col = [22, 24, 24, 24, 24, 26, 28, 30, 30, 30, 30, 30, 28, 26, 26, 24, 24, 20, 16, 14];
var str = [],
seatNo, className;
for (i = 0; i < col.length; i++) {
for (j = 0; j < col[i]; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
var bookedSeats = [];
init(bookedSeats);
$('.' + settings.seatCss).click(function() {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('Deze stoel is al bezet');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShow').click(function() {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function() {
var str = [],
item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
#holder {
height: 447px;
width: 667px;
background-color: #F5F5F5;
margin: auto;
border: 1px solid #A4A4A4;
position: relative;
}
#place {
display: table-row;
}
#place li {
display: table-cell;
vertical-align: middle;
list-style-type: none;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="holder">
<ul id="place">
</ul>
</div>
<div class="button">
<input type="button" id="btnShowNew" value="Keuze" />
</div>
http://jsfiddle.net/0bb4j5q7/
I suggest you use an ul for each line and center those. The way it is right now, the markup has no concept of lines inside a single ul, so you won't be able to center them.
Thanks for the help. I fixed it using "relative" for the parent and "absolute" and "vertical-align: middle for the list items.
#holder{
height: 447px;
width: 667px;
background-color: #F5F5F5;
margin: auto;
border: 1px solid #A4A4A4;
position: relative;
}
#place {
display: table-row;
}
#place li {
display: table-cell;
vertical-align: middle;
list-style-type: none;
position: absolute;
}

Categories