Sort the divs by content - javascript

I have a problem.
.titel
{
display: inline-block;
padding:5px 0 ;
}
#sort div div
{
display: inline-block;
padding:5px 0 ;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<div>
<div class="titel achternaam" >Achternaam</div>
<div class="titel voornaam" >Voornaam</div>
<div class="titel kantoor" >Kantoor</div>
</div>
<div class="spann">
<span class="ui-icon ui-icon-circle-triangle-n"></span>
<span class="ui-icon ui-icon-circle-triangle-s"></span>
<span class="ui-icon ui-icon-circle-triangle-n"></span>
<span class="ui-icon ui-icon-circle-triangle-s"></span>
<span class="ui-icon ui-icon-circle-triangle-n"></span>
<span class="ui-icon ui-icon-circle-triangle-s"></span>
</div>
<div id="sort">
<div class="someaspcode" onClick="someaspcodethatifyouclickitwilgotothepage">
<div class="achternaam">bill</div>
<div class="voornaam">gates</div>
<div class="kantoor">123</div>
</div>
<div class="someaspcode" onClick="someaspcodethatifyouclickitwilgotothepage">
<div class="achternaam">jhonny</div>
<div class="voornaam">depp</div>
<div class="kantoor">43321</div>
</div>
The data from div with id sort comes from a database (thats the reason ,that I show it like this)
What I whant to do is :
If I click on the first icon it shows the list sorted by voornaam(asc)
If I click on the second icon it shows the list sorted by voornaam(desc)
If I click on the third icon it shows the list sorted by achternaam (asc)
and so further
I have tried everything that I found on stackoverflow and google but none of it worked.
Can someone give me a good piece of advice.
what i whant is something like this
http://jsfiddle.net/7sgw21hn/1/
but it must read the content
things i tried
jQuery - Sorting div contents
https://www.sitepoint.com/community/t/sort-div-order-alphabetically-based-on-contents/39955/2
and many more (can't find it right now)
this is before i click
and this is after
can we do something about this

Here's the demo: http://output.jsbin.com/gojopuh
As mentioned, the first two buttons sort asc and desc on first name.
The second two buttons sort asc and desc on last name.
My code uses bubble sort and takes advantage of replaceChild for performance benefits.
Also with the code below, adding more controls for this data is now trivial.
Code below, any questions just ask.
var controls = document.querySelectorAll('.spann > span');
var dataContainer = document.querySelector('#sort');
var data = document.querySelectorAll('#sort > div');
// select controls
var ascAchternaam = controls[0];
var descAchternaam = controls[1];
var ascVoornaam = controls[2];
var descVoornaam = controls[3];
var ascKantoor = controls[4];
var descKantoor = controls[5];
var ascVerjaardag = controls[6];
var descVerjaardag = controls[7];
// define a user type
function User(achternaam, voornaam, kantoor, verjaardag, elem) {
this.achternaam = achternaam;
this.voornaam = voornaam;
this.kantoor = kantoor;
this.verjaardag = verjaardag;
this.elem = elem;
}
function bubbleSort(order, data, prop) {
// copy data array
var sortingArr = Array.prototype.slice.call(data);
for (var i = sortingArr.length - 1; i >= 0; i--) {
for (var j = 1; j <= i; j++) {
var birthdayA = sortingArr[j-1][prop].split('-');
var birthdayB = sortingArr[j][prop].split('-');
if (order == 'asc') {
if (birthdayA.length > 1) {
if (parseFloat(birthdayA[1], 10) > parseFloat(birthdayB[1], 10) || parseFloat(birthdayA[0], 10) > parseFloat(birthdayB[0], 10)) {
var temp = sortingArr[j-1];
sortingArr[j-1] = sortingArr[j];
sortingArr[j] = temp;
}
} else {
if (sortingArr[j-1][prop] > sortingArr[j][prop]) {
var temp = sortingArr[j-1];
sortingArr[j-1] = sortingArr[j];
sortingArr[j] = temp;
}
}
} else {
if (birthdayA.length > 1) {
if (parseFloat(birthdayA[1], 10) < parseFloat(birthdayB[1], 10) || parseFloat(birthdayA[0], 10) < parseFloat(birthdayB[0], 10)) {
var temp = sortingArr[j-1];
sortingArr[j-1] = sortingArr[j];
sortingArr[j] = temp;
}
} else {
if (sortingArr[j-1][prop] < sortingArr[j][prop]) {
var temp = sortingArr[j-1];
sortingArr[j-1] = sortingArr[j];
sortingArr[j] = temp;
}
}
}
}
}
return sortingArr;
}
// event action
function sortOnClick(order, data, prop) {
var sorted = bubbleSort(order, data, prop);
for (var i = 0; i < sorted.length; i++) {
var user = sorted[i];
var wrapper = user.elem.cloneNode(true);
dataContainer.replaceChild(wrapper, dataContainer.children[i]);
}
return sorted;
}
// used to make the data into a format we need
function formatUsers(data) {
var userData = [];
for (var i = 0; i < data.length; i++) {
var userElem = data[i];
var fname = userElem.querySelector('.achternaam').textContent;
var lname = userElem.querySelector('.voornaam').textContent;
var office = userElem.querySelector('.kantoor').textContent;
var birthday = userElem.querySelector('.verjaardag').textContent;
userData.push(new User(fname, lname, office, birthday, userElem));
}
return userData;
}
// sorter
function initSorter(data) {
// reshape our data
var userData = formatUsers(data);
// add event listeners to controls
ascAchternaam.addEventListener('click', function() {
sortOnClick('asc', userData, 'achternaam');
});
descAchternaam.addEventListener('click', function() {
sortOnClick('desc', userData, 'achternaam');
});
ascVoornaam.addEventListener('click', function() {
sortOnClick('asc', userData, 'voornaam');
});
descVoornaam.addEventListener('click', function() {
sortOnClick('desc', userData, 'voornaam');
});
ascKantoor.addEventListener('click', function() {
sortOnClick('asc', userData, 'kantoor');
});
descKantoor.addEventListener('click', function() {
sortOnClick('desc', userData, 'kantoor');
});
ascVerjaardag.addEventListener('click', function() {
sortOnClick('asc', userData, 'verjaardag');
});
descVerjaardag.addEventListener('click', function() {
sortOnClick('desc', userData, 'verjaardag');
});
}
// init our sorter
initSorter(data);

Let's give this a try then.
You do have to edit your HTML structure so that each 'record' of first name, last name and office has a seperate container. If you also have to go counting the amout of divs that make up one record, the code grows even larger.
I opted for a list as the wrappers, as it's more or less the standard way.
Also added a data-sort attribute to each of the icons so I don't have to go through the hassle of reading the sort type from the header.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.wrap-3, .wrap-6 {
border: 1px solid black;
width: 50%;
}
.wrap-3 > * {
display: inline-block;
width: 32%;
}
.wrap-6 > * {
display: inline-block;
width: 16%;
}
ul {
border: 1px solid black;
list-style: none;
width: 50%;
}
li {
display: block;
width: 100%;
}
li > * {
display: inline-block;
width: 32%;
}
</style>
</head>
<body>
<div class="wrap-3">
<span class="titel achternaam" >Achternaam</span>
<span class="titel voornaam" >Voornaam</span>
<span class="titel kantoor" >Kantoor</span>
</div>
<div id="icons-sort" class="wrap-6">
<span class="ui-icon ui-icon-circle-triangle-n" data-sort="achternaam-asc">up</span>
<span class="ui-icon ui-icon-circle-triangle-s" data-sort="achternaam-desc">down</span>
<span class="ui-icon ui-icon-circle-triangle-n" data-sort="voornaam-asc">up</span>
<span class="ui-icon ui-icon-circle-triangle-s" data-sort="voornaam-desc">down</span>
<span class="ui-icon ui-icon-circle-triangle-n" data-sort="kantoor-asc">up</span>
<span class="ui-icon ui-icon-circle-triangle-s" data-sort="kantoor-desc">down</span>
</div>
<ul>
<li>
<span class="achternaam">Gates</span>
<span class="voornaam">Bill</span>
<span class="kantoor">123</span>
</li>
<li>
<span class="achternaam">Zuckerberg</span>
<span class="voornaam">Mark</span>
<span class="kantoor">456</span>
</li>
<li>
<span class="achternaam">Resig</span>
<span class="voornaam">John</span>
<span class="kantoor">789</span>
</li>
</ul>
<script>
var clear = function clear( node ) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
return node;
};
document.querySelector('#icons-sort').addEventListener('click', function( event ) {
var list, records, fragment, sortType, field, order;
if (event.target && event.target.hasAttribute('data-sort')) {
list = document.querySelector('ul'),
records = Array.prototype.slice.call(list.querySelectorAll('li')),
fragment = document.createDocumentFragment(),
sortType = event.target.getAttribute('data-sort').split('-'),
field = '.' + sortType[0],
order = sortType[1];
records = records.sort(function( first, second ) {
var firstVal = first.querySelector(field).innerHTML,
secondVal = second.querySelector(field).innerHTML;
if (firstVal < secondVal) return -1;
else if (firstVal > secondVal) return 1;
});
if (order === 'desc') records.reverse();
records.forEach(function( listItem ) {
fragment.appendChild(listItem);
});
clear(list).appendChild(fragment);
}
});
</script>
</body>
</html>

Related

Trying to get values from multiple inputs

I'm trying to make a very basic expense tracker by building off the foundation of a todo app with vanilla Javascript. I'm having trouble isolating the value of all three input bars and getting them to display on the page. At the moment I'm getting 3 [objectHTMLInputElement] and undefined. I'd just like to know if I'm on the right track or if there's an easier way to isolate multiple input values and get them to display on the page. If somebody could point me in the right direction that'd be awesome. Thanks!
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let inputAll = document.querySelectorAll('.input-all');
let expenses = [
]
function add() {
let inputs = inputAll.value;
if (inputs == '') {
return true;
}
expenses.push(inputs);
displayExpenses();
}
function remove() {
}
function displayExpenses() {
let expensesUl = document.getElementById('expenses-ul');
expensesUl.innerHTML = `${inputName}${inputDate}${inputAmount}`;
for (var i = 0; i < expenses.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = expenses[i];
expensesUl.appendChild(expensesLi);
}
}
* {
padding: 0;
box-sizing: border-box;
}
.headings {
text-align: center;
}
.headings h1 {
font-size: 3rem;
font-family: 'Courier New', Courier, monospace;
}
.headings h2 {
margin-top: -20px;
}
form {
text-align: center;
}
#input-name {
width: 50%;
}
#input-date {
width: 18%;
margin-right: 160px;
}
#input-amount {
width: 18%;
margin-left: 18px;
}
#add-btn {
margin-top: 50px;
margin-left: 800px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Expense Tracker</title>
</head>
<body>
<div class="headings">
<h1>Expense Tracker</h1>
<h2>Add A New Item</h2>
</div>
<form>
<label>Name:</label>
<input class="input-all" id="input-name">
<br>
<br>
<label>Date:</label>
<input class="input-all" id="input-date">
<label>Amount:</label>
<input class="input-all" id="input-amount">
</form>
<button id="add-btn">Add Expense</button>
<ul id="expenses-ul"></ul>
<script src="main.js"></script>
</body>
</html>
Try this
const btn = document.getElementById('btn');
btn.addEventListener('click', function (event) {
const form = document.getElementById('form');
const output = document.getElementById('output');
const data = Object.fromEntries(new FormData(form).entries());
output.innerHTML = JSON.stringify(data, undefined, 2);
});
.wrap{
display: flex;
}
#output{
margin-left:50px;
border-width:3px;
border-style:dashed;
border-color:#FFAC55;
padding:5px;
min-width: 150px;
min-height: 80px;
}
<div class="wrap">
<div>
<form id="form">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="date">Date:</label><br>
<input type="text" id="role" name="role"> <br>
<label for="lname">Amount:</label><br>
<input type="text" id="amount" name="amount"><br><br>
<input id="btn" type="button" value="Print all value">
</form>
</div>
<div>
<pre id="output">
</pre>
</div>
</div>
When using document.querySelectorAll it's return a [NodeList] that consists of all selected elements on the other side there's also document.getElementsByClassName that return [HTMLCollection] - whatever you used you need to loop through to get the value of every selected input
When you passed [HTMLInputElement] as innerHTML of expensesUl it's will return the element object name not the value of this element because you are not selected any property of this object so you can't set an object as innerHTML of html element
if you want the right way of this part it's will be like that
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let expensesUl = document.getElementById('expenses-ul');
//this will give you empty string because they aren't get a value yet
expensesUl.innerHTML = `name = ${inputName.value}, date = ${inputDate.value}, amoute = ${inputAmount.value}`;
but now because we are selected all elements we are not need to select every input one by one anymore we will make a loop so we will loop through inputAll var to get the value of [HTMLInputElement] object
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
function add() {
let inputAll = document.querySelectorAll('.input-all');
for(var i of inputAll) {
if (i.value == '') {
return "Sorry you need to fill all inputs"
}
}
displayExpenses(inputAll);
}
function displayExpenses(elements) {
let expensesUl = document.getElementById('expenses-ul');
for (var i = 0; i < elements.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = elements[i].value
expensesUl.appendChild(expensesLi);
}
}
at the example above i removed expenses array but if you want to use it to take the value of the inputs you can make it like that
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
function add() {
let inputAll = document.querySelectorAll('.input-all');
let expenses = []
for(var i of inputAll) {
if (i.value == '') {
return "Sorry you need to fill all inputs"
}
expenses.push(i.value)
}
displayExpenses(expenses);
}
function displayExpenses(values) {
let expensesUl = document.getElementById('expenses-ul');
for (var i = 0; i < values.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = values[i]
expensesUl.appendChild(expensesLi);
}
}
the whole code should to be like that
let addButton = document.getElementById('add-btn');
addButton.addEventListener('click', add);
let inputName = document.getElementById('input-name');
let inputDate = document.getElementById('input-date');
let inputAmount = document.getElementById('input-amount');
let inputAll = document.querySelectorAll('.input-all');
let expenses = []
function add() {
for(var i of inputAll) {
if (i.value == '') {
return true
}
expenses.push(i.value)
}
displayExpenses();
}
function displayExpenses() {
let expensesUl = document.getElementById('expenses-ul');
expensesUl.innerHTML = `${inputName.value}, ${inputDate.value}, ${inputAmount.value}`;
for (var i = 0; i < expenses.length; i++) {
let expensesLi = document.createElement('li');
expensesLi.innerHTML = expenses[i];
expensesUl.appendChild(expensesLi);
}
}
about document.getElementsByClassName, document.querySelectorAll one deferant is that you can use array methods like forEach() with document.querySelectorAll while you can't do that with document.getElementsByClassName

Want to remove previously appended table

When I Click on submit button after clicking on the links it appends perfectly but when I hit the button again it doesn't remove previously appended table.
I want to clear the previously created table when user clicks on the cross button and then print the table again or else overwrite the table but instead it is not removing the table and prints a new one.Image Part OneImage Part TwoImage Part ThreeImage Part Four
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(" + i + ")'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
}
//To Remove The Specific Element User Want To Delete
function remove(id) {
orders_list.splice(id, id);
loop("t");
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>
Update your remove function as function remove(el) { el.closest('table').remove(); }.
Update parameter in html as "</td><td onclick='remove(this)'>×</td></tr>".
And add orders_list = []; in the end of loop function.
Try it below.
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(this)'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
orders_list = [];
}
//To Remove The Specific Element User Want To Delete
function remove(el) {
el.closest('table').remove();
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>

Not able to get selected word using jQuery UI selectable

I am trying to make an annotation tool, where I will select some words and get their relative start and indices in the sentence.
I am using jQuery UI's selectable tool to select word(s) and get their data attributes out of them.
In this example, I want to select the splitted word(s): (HELLO, ,, WORLD, .) and get their data attributes out of them.
My hierarchy of div(s) is as follows:
#tblText > tbody > tr > td > #0 > div#div0.uiselectee.ui-selected
$(function() {
$('#btnAddUtterance').click(function() {
populateUtterance();
});
var selected1 = new Array();
$(".tokenized").selectable({
selected: function(event, ui) {
debugger;
alert(ui.selected.innerHTML);
selected1.push(ui.selected.id);
},
unselected: function(event, ui) {
//ui.unselected.id
}
});
var uttIdx = 0;
var tokenizedUtterances = new Array();
function populateUtterance() {
let userUtterance = $('#myInput').val();
let tokenizedUtterance = tokenizeUtterance(userUtterance, uttIdx);
let markup = `<tr><td><input type='checkbox' name='record'></td><td> ${tokenizedUtterance} </td> <td>${userUtterance}</td></tr>`;
$("#tblText tbody").append(markup);
uttIdx += 1;
$('#myInput').val('');
}
$("#myInput").keyup(function(event) {
if (event.keyCode === 13) {
populateUtterance();
}
});
function findSpacesIndex(utterance) {
let index = 0;
let spacesIndex = [];
while ((index = utterance.indexOf(' ', index + 1)) > 0) {
spacesIndex.push(index);
}
return spacesIndex;
}
function createUtteranceLookup(utterance) {
let lookUpObject = new Array();
utterance.replace(/[\w'-]+|[^\w\s]+/g, (word, offset) =>
lookUpObject.push({
word: word,
start: offset,
end: offset + word.length
}));
return lookUpObject;
}
function tokenizeUtterance(utterance) {
let div = `<div id=${uttIdx} class ='tokenizedUtterance'>`;
let spacesIndex = new Array();
spacesIndex = findSpacesIndex(utterance);
let utteranceLookup = new Array();
for (let i = 0; i < spacesIndex.length; i++) {
utteranceLookup.push({
word: " ",
start: spacesIndex[i],
end: spacesIndex[i]
});
}
let wordsIndex = [];
wordsIndex = createUtteranceLookup(utterance);
Array.prototype.push.apply(utteranceLookup, wordsIndex);
utteranceLookup.sort(function(obj1, obj2) {
return obj1.start - obj2.start;
});
for (let i = 0; i < utteranceLookup.length; i++)
utteranceLookup[i]["wordIndexInSentence"] = i;
$.each(wordsIndex, function(index, item) {
let divId = "div" + index;
let divStart = item.start;
let divEnd = item.end;
let divValue = item.word;
div += `<div style="display:inline-block;margin:5px; border: 1px solid black;" id = "${divId}" data-start=${divStart} data-end= ${divEnd} data-value= "${divValue}"> ${item.word} </div >`;
});
tokenizedUtterances.push({
UtteranceNumber: uttIdx,
tokenizedUtteranceLookup: utteranceLookup
});
div += '</div>';
$('#testOutput').html('');
$('#testOutput').html(JSON.stringify(tokenizedUtterances, undefined, 2));
utteranceLookup = new Array();
return div;
}
$(document).on("click", '#tblText > tbody > tr > td:nth-child(2)', function(event) {
//if ctrl key or left click is pressed, select tokenized word
if (event.ctrlKey || event.which === 1) {
$('.tokenizedUtterance').selectable();
}
console.log("Selected");
});
// Find and remove selected table rows
$(document).on('click', '#btnDeleteRow', function(e) {
$("#tblText tbody").find('input[name="record"]').each(function() {
if ($(this).is(":checked")) {
$(this).parents("tr").remove();
$('#testOutput').html('');
}
});
});
});
.tokenizedUtterance .ui-selecting {
background: #FFFF99;
}
.tokenizedUtterance .ui-selected {
background: #FFFF00;
font-family: 'Segoe UI';
font-style: italic
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<h2>AnnotationView</h2>
<h2>Enter text to annotate</h2>
<input type="text" id="myInput" />
<button id="btnAddUtterance" class="btn btn-info">Add Utterance</button>
<table id="tblText" class="table table-hover">
<thead>
<tr>
<th>Select</th>
<th>Tokenized User Utterance</th>
<th>Original Utterance</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button id='btnDeleteRow' class='btn btn-danger'>Delete Utterance</button>
<span>You've selected:</span> <span id="select-result"></span>.
<hr />
<h1>Output is: </h1> <br />
<pre id="testOutput" style="word-wrap: break-word; white-space: pre-wrap;"></pre>
Here's a Fiddle of the app
Any help will be greatly appreciated.
I believe this is what you are looking for - PEN
We can make use of the selected and unselecting events in the Selectable Widget.
The selected elements are stored in a variable elem. Hope you can use this variable to access the data variables and construct the JSON. Please let me know whether this helps.

Angular : Display data item stored in an array one by one

I've a simple situation, where I've a bunch of data stored in an array.
I want to display the array in html view, one by one, when the next/prev buttons are clicked.
I followed this : How to show item from json Array one by one in Angular JS
However, My code doesn't seem to work.
Code :
/**
* Created by PBC on 5/21/2016.
*/
var solver = angular.module('solver', []);
solver.controller('data', data);
function data($scope, $http){
$scope.Type = "";
$scope.qlist = [];
$scope.alist = [];
$scope.idx = 0;
$scope.ans = "";
$scope.q = "";
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
};
var data = $.param({
_Down_Questions:localStorage.getItem('prb')
});
$http.post("../Php/download_questions.php", data, config).then
(
//Success Callback
function (res) {
$scope.Type = res.data.Type;
if ($scope.Type == 'Objective'){
for(var i = 0; i < res.data.Data.length; i++){
var data = {Q:res.data.Data[i]["Q"], A:res.data.Data[i]["A"]};
$scope.qlist[i] = data;
}
}
else{
for(var i = 0; i < res.data.Data.length; i++){
var data = {Q:res.data.Data[i]["Q"], A:res.data.Data[i]["A"], O:res.data.Data[i]["O"]};
$scope.qlist.push[i] = data;
}
}
},
//Error Callback
function () {
$scope.registrationResponse = "";
swal("Request couldn't be sent!", "", "error");
}
);
$scope.next = function () {
if ($scope.idx < res.data.Data.length){
$scope.alist[$scope.idx] = $scope.ans;
$scope.idx += 1;
$scope.ans = null;
}
};
$scope.prev = function () {
if ($scope.idx > 0){
$scope.idx -= 1;
ans = $scope.alist[$scope.idx];
}
};
}
using this, in the html as :
<div data-ng-controller="data">
<div style="display: table;margin: 0 auto; width: 30%">
<div class="row container" style="margin-top: 50%">
<div class="col l12" data-ng-repeat="q in qlist track by $index" data-ng-show="$index == idx">
{{q[idx]["Q"]}}
</div>
<input placeholder="Answer" data-ng-model="ans" type="text" class="validate center">
<div class="row" style="display: table;margin: 0 auto; width: 100%">
<a class="waves-effect waves-light btn" data-ng-click="next()" style="display: table;margin: 0 auto; width: 50%">Next</a><br>
<a class="waves-effect waves-light btn" data-ng-click="prev()" style="display: table;margin: 0 auto; width: 50%">Previous</a>
</div>
</div>
</div>
</div>
What am I doing wrong ?
I've found the mistakes:
1)
{{q[idx]["Q"]}}
should be
{{q["Q"]}}
2)
$scope.next = function () {
if ($scope.idx < res.data.Data.length){
$scope.alist[$scope.idx] = $scope.ans;
$scope.idx += 1;
$scope.ans = null;
}
};
Here, the condition was wrong :
it should be,
if ($scope.idx < $scope.qlist.length){

slideUp() all the elements but not the selected ones

All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>

Categories

Resources