how to remove added item in cart? - javascript

i am trying make drag and drop shopping cart. By the help from some site on internet i am able to add the item in the cart and also it calculates the total price. But i am unable to remove a selected item fro the cart. I am very new to javascript and html5, so please help me..
the code is:
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var items = document.querySelectorAll("section.products ul li");
var cart = document.querySelectorAll("#cart ul")[0];
function updateCart(){
var total = 0.0;
var cart_items = document.querySelectorAll("#cart ul li")
for (var i = 0; i < cart_items.length; i++) {
var cart_item = cart_items[i];
var quantity = cart_item.getAttribute('data-quantity');
var price = cart_item.getAttribute('data-price');
var sub_total = parseFloat(quantity * parseFloat(price));
cart_item.querySelectorAll("span.sub-total")[0].innerHTML = " = " + sub_total.toFixed(2);
total += sub_total;
}
document.querySelectorAll("#cart span.total")[0].innerHTML = total.toFixed(2);
}
function addCartItem(item, id) {
var clone = item.cloneNode(true);
clone.setAttribute('data-id', id);
clone.setAttribute('data-quantity', 1);
var btn=document.createElement('BUTTON');
btn.className = 'remove-item';
var t=document.createTextNode("X");
btn.appendChild(t);
cart.appendChild(btn);
clone.removeAttribute('id');
fragment = document.createElement('span');
fragment.setAttribute('class', 'sub-total');
clone.appendChild(fragment);
cart.appendChild(clone);
$('#product').on('click','.remove-item',function(){
$(this).closest('li').remove();// remove the closest li item row
});
}
function updateCartItem(item){
var quantity = item.getAttribute('data-quantity');
quantity = parseInt(quantity) + 1
item.setAttribute('data-quantity', quantity);
var span = item.querySelectorAll('span.quantity');
span[0].innerHTML = ' x ' + quantity;
}
function onDrop(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var id = event.dataTransfer.getData("Text");
var item = document.getElementById(id);
var exists = document.querySelectorAll("#cart ul li[data-id='" + id + "']");
if(exists.length > 0){
alert("Already present");
} else {
addCartItem(item, id);
}
updateCart();
return false;
}
function onDragOver(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
return false;
}
addEvent(cart, 'drop', onDrop);
addEvent(cart, 'dragover', onDragOver);
function onDrag(event){
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.dropEffect = "move";
var target = event.target || event.srcElement;
var success = event.dataTransfer.setData('Text', target.id);
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
item.setAttribute("draggable", "true");
addEvent(item, 'dragstart', onDrag);
};
});
</script>
and
<section id="product">
<ul class="clear">
<li data-id="1">
<a href="#">
<img src="a.jpg" alt="">
<h3>item 1</h3>
<p>xyz</p>
</a>
</li>
</ul>
</secton>
and css is:
<style>
ul, li{
list-style: none;
margin: 0px;
padding: 0px;
cursor: pointer;
}
section#cart ul{
height: 200px;
overflow: auto;
background-color: #cccccc;
}
</style>

Add a close button to every cart item like
<input type="button" class="remove-item" value="X" />
Try this to remove the item-row,
$('#product').on('click','.remove-item',function(){
$(this).closest('li').remove();// remove the closest li item row
});

Then Try this to remove the item in the cart
$(".remove").click(function(e) {
pid = $(this).siblings("#checkIDinput:hidden").attr("value");
Or--------------------
$(".remove").click(function(e) {
pid = $(this).siblings("input:hidden").attr("value");

Related

Remove Active Element With JavaScript

I'm trying to add some validation on something I'm working on. Basically if no input is processed, it would return a red paragraph telling you to enter something and return false. The problem I'm having is how to remove it when a valid value is processed.
var input = document.getElementById('input'),
button = document.getElementById('add')
function removeItem() {
var item = this.parentNode
var parent = item.parentNode
parent.removeChild(item)
}
button.addEventListener('click', function (e) {
if (input.value === '') {
var p = document.querySelector('p')
p.style.display = 'block'
return false
} else if (!input.value === '') {
p.style.display = ''
return true
}
var userInput = document.createTextNode(input.value)
var li = document.createElement('li')
var ul = document.getElementById('todo')
var remove = document.createElement('button')
remove.innerHTML = 'Remove'
remove.addEventListener('click', removeItem);
ul.insertBefore(li, ul.childNodes[0])
li.appendChild(userInput)
li.appendChild(remove)
})
<input type="text" id="input"/>
<button id="add">Add</button>
<p>plz add</p>
<div class="container">
<ul id="todo"></ul>
</div>
p {
display: none;
color: #f00;
}
Some issues:
You return in both if ... else cases, which (if it would work) makes the rest of the code unreachable.
The else if condition is unnecessary (since the if condition was already false), but is also wrong: ! has precedence over ===, so better use !==. Anyway, it is not needed at all.
Here is the corrected code:
var input = document.getElementById('input'),
button = document.getElementById('add');
function removeItem() {
var item = this.parentNode;
var parent = item.parentNode;
parent.removeChild(item);
}
button.addEventListener('click', function(e) {
var p = document.querySelector('p');
if (input.value.trim() === '') {
p.style.display = 'block';
return false;
}
p.style.display = '';
var remove = document.createElement('button');
remove.textContent = 'Remove';
remove.addEventListener('click', removeItem);
var li = document.createElement('li');
li.appendChild(document.createTextNode(input.value));
li.appendChild(remove);
todo.insertBefore(li, todo.childNodes[0]);
});
p {
display: none;
color: #f00;
}
<input type="text" id="input"/>
<button id="add">Add</button>
<p>plz add</p>
<div class="container">
<ul id="todo"></ul>
</div>
add an id to the error element. Then :
var el = document.getElementById('theidyouset')
el.parentNode.removeChild( el );
or you could hide it
el.className += " classhiddenwithcss";
Use CSS classes and simply add or remove the class from the class list as needed.
Also, because you are using return in both of your if/else cases, the code will stop processing and not continue on to do the rest of the work. Move the if/else to the end of the code so that return is the last thing you do.
And, use semi-colons at the end of your statements.
var input = document.getElementById('input'),
button = document.getElementById('add')
function removeItem() {
var item = this.parentNode;
var parent = item.parentNode;
parent.removeChild(item);
}
button.addEventListener('click', function(e) {
var p = document.querySelector('p')
var userInput = document.createTextNode(input.value)
var li = document.createElement('li')
var ul = document.getElementById('todo')
var remove = document.createElement('button')
remove.innerHTML = 'Remove'
remove.addEventListener('click', removeItem);
ul.insertBefore(li, ul.childNodes[0])
li.appendChild(userInput)
li.appendChild(remove)
if (input.value === '') {
p.classList.remove("hidden");
return false;
} else {
p.classList.add("hidden");
return true;
}
})
p {
color: #f00;
}
.hidden {
display:none;
}
<input type="text" id="input"/>
<button id="add">Add</button>
<p class="hidden">plz add</p>
<div class="container">
<ul id="todo"></ul>
</div>

How to save html page content in .txt file using JavaScript?

I have create a static html page for quiz.
Following is my code
<style>
body {
font-family: Open Sans;
}
#quiz {display:none;}
#prev {display:none;}
#start {display:none;}
#submit{display:none;}
ul{list-style:outside none none; margin:0px; padding:0px;}
.question>div>div>div>p{ color: #fff;
background-color: #337ab7;
padding: 6px;
border-radius: 3px;}
.navbar-default {background-color: #fff;border-color: #ddd; border-radius:0px;}
</style>
<body>
<div class='container question'>
<div class='row'>
<div class='col col-md-12' id='quiz'>
</div>
</div>
</div>
<div class='container question' >
<div class='row' id='quiz'>
</div>
</div>
<br/>
<div class='container'>
<a href='#' class='btn btn-md btn-default pull-right' id='next'>Next</a>
<a href='#' class='btn btn-md btn-default pull-left' id='prev'>Prev</a>
<a href='#' class='btn btn-md btn-default' id='start'>Start Over</a>
<div class='button' id='submit' style='display:none;'>
<input type='text' placeholder='Name' id="inputFileNameToSaveAs"/>
<button type='submit' class='btn btn-success' onclick="saveTextAsFile()">Submit</button>
</div>
</div>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script type="text/javascript">
function saveTextAsFile()
{
var textToSave = document.getElementById("question").text;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
(function() {
var questions = [
{
question: "Which one is correct?",
choices: ['a!=b', 'a=!b', 'a:=b', 'a=-b'],
correctAnswer: 0
},
];
var questionCounter = 0; //Tracks question number
var selections = []; //Array containing user choices
var quiz = $('#quiz'); //Quiz div object
// Display initial question
displayNext();
// Click handler for the 'next' button
$('#next').on('click', function (e) {
e.preventDefault();
// Suspend click listener during fade animation
if(quiz.is(':animated')) {
return false;
}
choose();
// If no user selection, progress is stopped
if (isNaN(selections[questionCounter])) {
alert('Please make a selection!');
} else {
questionCounter++;
displayNext();
}
});
// Click handler for the 'prev' button
$('#prev').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
choose();
questionCounter--;
displayNext();
});
// Click handler for the 'Start Over' button
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
questionCounter = 0;
selections = [];
displayNext();
$('#start').hide();
});
// Animates buttons on hover
$('.button').on('mouseenter', function () {
$(this).addClass('active');
});
$('.button').on('mouseleave', function () {
$(this).removeClass('active');
});
// Creates and returns the div that contains the questions and
// the answer selections
function createQuestionElement(index) {
var qElement = $('<div>', {
id: 'question'
});
var header = $('<p>Question ' + (index + 1) + '</p>');
qElement.append(header);
var question = $('<h3>').append(questions[index].question);
qElement.append(question);
var radioButtons = createRadios(index);
qElement.append(radioButtons);
return qElement;
}
// Creates a list of the answer choices as radio inputs
function createRadios(index) {
var radioList = $('<ul>');
var item;
var input = '';
for (var i = 0; i < questions[index].choices.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += questions[index].choices[i];
item.append(input);
radioList.append(item);
}
return radioList;
}
// Reads the user selection and pushes the value to an array
function choose() {
selections[questionCounter] = +$('input[name="answer"]:checked').val();
}
// Displays next requested element
function displayNext() {
quiz.fadeOut(function() {
$('#question').remove();
if(questionCounter < questions.length){
var nextQuestion = createQuestionElement(questionCounter);
quiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value='+selections[questionCounter]+']').prop('checked', true);
}
// Controls display of 'prev' button
if(questionCounter === 1){
$('#prev').show();
} else if(questionCounter === 0){
$('#prev').hide();
$('#next').show();
}
}else {
var scoreElem = displayScore();
quiz.append(scoreElem).fadeIn();
$('#next').hide();
$('#prev').hide();
$('#start').show();
$('#submit').show();
}
});
}
// Computes score and returns a paragraph element to be displayed
function displayScore() {
var score = $('<h4>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect++;
}
}
score.append('You got ' + numCorrect + ' questions out of ' +
questions.length + ' right!!!');
return score;
}
})();
</script>
</body>
all is working fine but i want to save the checked radio button value and final result in .txt file
i want to save all the answers by user and along with the correct and the wrong to.
Things to note :
- initialize the variable textToSave first with no value;
- document.getElementById("question").text; Should be document.getElementById("question").innerHTML;
- in the body of choose, add the value of radio to the variable textToSave
And the result
var textToSave='';
function saveTextAsFile()
{
textToSave += ". Final Result : "+document.getElementById("question").innerHTML;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
(function() {
var questions = [
{
question: "Which one is correct?",
choices: ['a!=b', 'a=!b', 'a:=b', 'a=-b'],
correctAnswer: 0
},
];
var questionCounter = 0; //Tracks question number
var selections = []; //Array containing user choices
var quiz = $('#quiz'); //Quiz div object
// Display initial question
displayNext();
// Click handler for the 'next' button
$('#next').on('click', function (e) {
e.preventDefault();
// Suspend click listener during fade animation
if(quiz.is(':animated')) {
return false;
}
choose();
// If no user selection, progress is stopped
if (isNaN(selections[questionCounter])) {
alert('Please make a selection!');
} else {
questionCounter++;
displayNext();
}
});
// Click handler for the 'prev' button
$('#prev').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
choose();
questionCounter--;
displayNext();
});
// Click handler for the 'Start Over' button
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
questionCounter = 0;
selections = [];
displayNext();
$('#start').hide();
});
// Animates buttons on hover
$('.button').on('mouseenter', function () {
$(this).addClass('active');
});
$('.button').on('mouseleave', function () {
$(this).removeClass('active');
});
// Creates and returns the div that contains the questions and
// the answer selections
function createQuestionElement(index) {
var qElement = $('<div>', {
id: 'question'
});
var header = $('<p>Question ' + (index + 1) + '</p>');
qElement.append(header);
var question = $('<h3>').append(questions[index].question);
qElement.append(question);
var radioButtons = createRadios(index);
qElement.append(radioButtons);
return qElement;
}
// Creates a list of the answer choices as radio inputs
function createRadios(index) {
var radioList = $('<ul>');
var item;
var input = '';
for (var i = 0; i < questions[index].choices.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += questions[index].choices[i];
item.append(input);
radioList.append(item);
}
return radioList;
}
// Reads the user selection and pushes the value to an array
function choose() {
selections[questionCounter] = +$('input[name="answer"]:checked').val();
textToSave += "Choosen Value : "+selections[questionCounter];
}
// Displays next requested element
function displayNext() {
quiz.fadeOut(function() {
$('#question').remove();
if(questionCounter < questions.length){
var nextQuestion = createQuestionElement(questionCounter);
quiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value='+selections[questionCounter]+']').prop('checked', true);
}
// Controls display of 'prev' button
if(questionCounter === 1){
$('#prev').show();
} else if(questionCounter === 0){
$('#prev').hide();
$('#next').show();
}
}else {
var scoreElem = displayScore();
quiz.append(scoreElem).fadeIn();
$('#next').hide();
$('#prev').hide();
$('#start').show();
$('#submit').show();
}
});
}
// Computes score and returns a paragraph element to be displayed
function displayScore() {
var score = $('<h4>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect++;
}
}
score.append('You got ' + numCorrect + ' questions out of ' +
questions.length + ' right!!!');
return score;
}
})();
<style>
body {
font-family: Open Sans;
}
#quiz {display:none;}
#prev {display:none;}
#start {display:none;}
#submit{display:none;}
ul{list-style:outside none none; margin:0px; padding:0px;}
.question>div>div>div>p{ color: #fff;
background-color: #337ab7;
padding: 6px;
border-radius: 3px;}
.navbar-default {background-color: #fff;border-color: #ddd; border-radius:0px;}
</style>
<body>
<div class='container question'>
<div class='row'>
<div class='col col-md-12' id='quiz'>
</div>
</div>
</div>
<div class='container question' >
<div class='row' id='quiz'>
</div>
</div>
<br/>
<div class='container'>
<a href='#' class='btn btn-md btn-default pull-right' id='next'>Next</a>
<a href='#' class='btn btn-md btn-default pull-left' id='prev'>Prev</a>
<a href='#' class='btn btn-md btn-default' id='start'>Start Over</a>
<div class='button' id='submit' style='display:none;'>
<input type='text' placeholder='Name' id="inputFileNameToSaveAs"/>
<button type='submit' class='btn btn-success' onclick="saveTextAsFile()">Submit</button>
</div>
</div>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
</body>
I assume you want to save the data for yourself, not the end user.
If you are looking to generate a txt file and download it - You can refer answer from Sagar V.
You can't directly save your answers or whatever data into a file by using JavaScript from a web browser.
You neeed a small server, maybe in node.js , php or java
First format your answers in particular structure like json and sene it as POST request method parameter
In server parse your parameter and save to an file you need
function downloadFile(filename, content) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}

Sort the divs by content

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>

Add and Remove class to click a dynamic Button

Trying to Add and Remove class to click dynamic Buttons, means this button <button class="one"></button> get class dynamically like this: <button class="one text1">text1</button>
So if button one has class .text1 and by click this add class .hide to list item <li class="text1"> like <li class="text1 show">
Same for button two <button class="two"></button> and by click add class <li class="text2 show">
Note: when click button two, then should remove class .show and add new class .hideto button one.
Main HTML:
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>
Script:
$('.label a').each(function() {
var $this=$(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function(){
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function(){
if(clses.indexOf($(this).attr('class')) === -1){
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if(ind === liInd){
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
See Example on Fiddle
I have tried this by add/remove class by click function, but problem is Buttons get class dynamically from List items, so I'm not able to target button.
Any suggestion for other way to do this by JS/ Jquery?
Here is an alternative solution
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
if (txt != '') {
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
}
});
$('button').click(function () {
if ($(this).attr('class')[0] == 'all') {
showAll();
return false; // end this function
}
var allCls = $(this).attr('class').split(' ');
$('li').each(function () {
if (allCls.indexOf($(this).find('a').text()) > -1) {
$(this).closest('li').removeClass('show').addClass('hide');
} else {
$(this).closest('li').removeClass('hide').addClass('show');
}
});
});
function showAll() {
$('li').removeClass('hide').addClass('show');
}
Fiddle: https://jsfiddle.net/taleebanwar/yaLm4euk/13/
DEMO
$('.label a').each(function () {
var $this = $(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
$(document).on('click', 'button',function(e){
var textClass = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('text') === 0;
}).join();
console.log(textClass);
$('li').removeClass('show').addClass('hide')
$('li').each(function(){
if($(this).hasClass($.trim(textClass))){
$(this).removeClass('hide').addClass('show');
} else {
$(this).removeClass('show').addClass('hide');
}
})
})
.show{display:list-item;}
.hide{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>

update total with multiple list items by clicking on images

So I'm not entirely sure what I'm missing, but I can't seem to get the total price to add properly. I can get each individual price, though.
Basically the idea is to click on a grayed out image, it generates a list(working) and it's suppose to give a price(which is does) and if you click on another image it should update the price, which would add to the previous price.
Can someone please tell me what I'm missing or doing wrong?
Here is my fiddle: http://jsfiddle.net/lolsen7/Acnx4/2/
HTML:
<div id="station-builder">
<a class="tools4" href="#"> <img id="keyboard" class="part" src="http://placehold.it/100x100" alt="Keyboard"/><span class="info">apple keyboard</span></a>
<a class="tools5" href="#"><img id="mouse2" class="part" src="http://placehold.it/100x100" alt="Mouse" ><span class="info">apple mouse</span></a
</div>
<div id="summaryTotal">
<p>Get this system for as little as:</p>
</div>
<ul id="list">
<li>2201L elo Touchscreen monitor</li>
<li>Mac mini</li>
</ul>
Javascript:
$ //JS FOR HARDWARE SECTION
$(document).ready(function () {
$(".part").mouseover(function () {
if (this.className !== 'part selected') {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
}
$(this).mouseout(function () {
if (this.className !== 'part selected') {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
}
});
});
var list = document.getElementById("list");
var summaryTotal = document.getElementById("summaryTotal");
var sum = 0;
var total = 0;
var finalTotal = 0;
$(".part").click(function () {
if (this.className == 'part') {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
console.log(this);
if (this.id == 'keyboard') {
var li = document.createElement("li");
//li.setAttribute("alt","keyboard_li");
li.setAttribute("id", "keyboard_li");
li.appendChild(document.createTextNode('Keyboard'));
list.appendChild(li);
var keyboardPrice = "59";
sum = keyboardPrice * 1.2;
console.log(sum);
total = sum / 40;
console.log(total);
var span = document.createElement('span');
span.setAttribute('id', 'keyboardTotal');
summaryTotal.appendChild(span);
$('#keyboardTotal').append(total);
}
if (this.id == 'mouse2') {
li = document.createElement("li");
li.setAttribute("id", "mouse_li");
li.appendChild(document.createTextNode('Mouse'));
list.appendChild(li);
var mousePrice = "59";
sum = mousePrice * 1.2;
console.log(sum);
total = sum / 40;
console.log(total);
var span = document.createElement('span');
span.setAttribute('id', 'mouseTotal');
summaryTotal.appendChild(span);
$('#mouseTotal').append(total);
}
} else {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
console.log(this);
if (this.id == "keyboard") {
$("#keyboard_li").remove();
$('#keyboardTotal').remove();
}
if (this.id == "mouse2") {
$("#mouse_li").remove();
}
}
$(this).toggleClass('selected');
});
total = $('#keyboardTotal') + $('#mouseTotal');
});
Can you make the following changes?
var kbtotal = 0;//added
var mstotal = 0;//added
var keyboardPrice = 59;
sum = keyboardPrice * 1.2;
console.log(sum);
kbtotal = sum / 40; // changed
console.log(kbtotal); // changed
var mousePrice = 59;
sum = mousePrice * 1.2;
console.log(sum);
mstotal = sum / 40; // changed
console.log(mstotal); // changed
var finaltotal = parseFloat(kbtotal) + parseFloat(mstotal);
$('#finaltotal').text(finaltotal); // added
<div id="summaryTotal">
<p>Get this system for as little as: <div id="finaltotal"></div></p>
</div>

Categories

Resources