I am supposed to build a store for a a javascript assignment. The store has three items and a counter which tallies the total of the items. Each item is updated through a click event which changes the value based on a data attribute defined in the html. It then saves this to cookies and allows us to use what was stored when we get to a checkout page. The cookies store and the totals update, but unfortunately, each time the click event occurs, the image disappears. I have been scouring the code and I cannot see why this is happening. Can anyone help?
$(document).ready(function() {
$("#jeans-line").text(Cookies.get("jeans") || 0)
$("#jeanJacket-line").text(Cookies.get("jeanJacket") || 0)
$("#belt-line").text(Cookies.get("belt") || 0)
$("#total").text(Cookies.get("total") || 0)
//The DOM will be changed to the key value of each cookie or 0
$('.item').click(function() {
itemTotal = parseInt($(this).text())
oneMore = itemTotal + ($(this).data('cost'))
$(this).text(oneMore)
Cookies.set($(this).data('name'), oneMore)
setTotal()
});
// //updating the total cost of the pseudo-items in shopping
function setTotal() {
var jeans = parseInt(Cookies.get("jeans"))
var jeanJacket = parseInt(Cookies.get("jeanJacket"))
var belt = parseInt(Cookies.get("belt"))
Cookies.set("total", (jeans + jeanJacket + belt) || 0)
$("#total").text(Cookies.get("total") || 0)
};
//Enter data and close the modal
var modal = $("#modal-box")
var email_input;
$(".email-submit").click(function(e) {
e.preventDefault();
email_input = $("#email-val").val()
console.log(email_input)
var checkEmail = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (checkEmail.test(email_input)) {
alert("This is a good email!")
Cookies.set("email", email_input)
modal.css("display", "none")
} else {
alert("This is not a valid email address!")
}
});
//closes the model with close click event
$(".close").click(function() {
modal.css("display", "none");
});
}) //closes document.ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-4">
<div class="item" data-cost="200" data-name="jeans">
<img id="jeansIMG" src="images/jeans.jpg">
<h2 class="item" id="jeans-line"></h2>
</div>
</div>
<div class="col-md-4">
<div class="item" data-cost="300" data-name="jeanJacket">
<img id="jeanJacketIMG" src="images/jean_jacket.jpg">
<h2 class="item" id="jeanJacket-line"></h2>
</div>
</div>
<div class="col-md-4">
<div class="item" data-cost="50" data-name="belt">
<img id="beltIMG" src="images/belt.jpg">
<h2 class="item" id="belt-line"></h2>
</div>
</div>
</div>
<!-- closes the bootstrap row -->
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-4">
<img class="shoppingCart" src="images/shopping_cart.jpg">
<h2 class="totalTitle">The total for these pseudo-products is:</h2>
<h2 id="total"></h2>
</div>
<div class="col-md-4">
</div>
</div>
The reason why images are getting remove is because of this code:
$('.item').click(function () {
itemTotal = parseInt($(this).text())
oneMore = itemTotal + ($(this).data('cost'))
$(this).text(oneMore) // <-- this overrides everything inside div.item
Cookies.set($(this).data('name'), oneMore)
setTotal()
});
Seeing your overall code, I'd suggest to change inner item class to something else (eg. item-total) so it won't be conflicting with the outer item class. After that adjust the javascript code:
$('.item').click(function() {
itemTotal = parseInt($(this).text())
oneMore = itemTotal + ($(this).data('cost'))
$('.item-total', this).text(oneMore) // <!-- change text in item-total
Cookies.set($(this).data('name'), oneMore)
setTotal()
});
You may also want to modify the setTotal to add default value || 0 so that it will calculate the total properly even if there is one or more items left unclicked:
function setTotal() {
var jeans = parseInt(Cookies.get("jeans") || 0)
var jeanJacket = parseInt(Cookies.get("jeanJacket") || 0)
var belt = parseInt(Cookies.get("belt") || 0)
Cookies.set("total", (jeans + jeanJacket + belt) || 0)
$("#total").text(Cookies.get("total") || 0)
};
You can check the simplified demo in https://jsfiddle.net/nm5dL9h1/
Related
I have an array of objects. Each object contain few parameters. What I am trying to do is to run over the array and get from each cell the data and present it on a tabel/grid.
Example code
function addButton(){
var phoneNumber = document.getElementById("phoneNumber").value;
var email = document.getElementById("email").value;
var typeNotification = document.getElementById("typeNotification").value;
var valueNumber = document.getElementById("valueNumber").value;
var delayLimit = document.getElementById("delayLimit").value;
var timeStart = document.getElementById("timeStart").value;
var timeEnd = document.getElementById("timeEnd").value;
var notify = {
typeNotification : typeNotification,
email : email,
delayLimit : delayLimit,
timeStart : timeStart,
timeEnd : timeEnd,
valueNumber : valueNumber,
phoneNumber : phoneNumber
};
var notificationList = [];
notificationList.push(notify);
console.log(notificationList);
var notificationListLength = notificationList.length;
for(var i = 0;i < notificationListLength;i++){
<div class="container">
<div class="row">
<div class="col">
1 of 2
</div>
<div class="col">
2 of 2
</div>
</div>
<div class="row">
<div class="col">
1 of 3
</div>
<div class="col">
2 of 3
</div>
<div class="col">
3 of 3
</div>
</div>
</div>
}
}
Inside the loop it gives me error with the Tags.
As you can see, when the user press the AddButton it gets all the data and restore it in object, then I add the object into Array, and then I run on the array and get from each cell of the array the data and I want to show it in Grid.
Like I said it gives me error inside the loop with the tags.
Any idea how can I solve it?
You need to build up the output of html/tags you want, then add that to a targeted element on the page, like so:
<div id="target"></div>
<button onclick="addButton()">Add</button>
<script>
const
target = document.querySelector('#target'),
notificationList = [{
typeNotification: 'typeNotification',
email: 'email',
delayLimit: 'delayLimit',
timeStart: 'timeStart',
timeEnd: 'timeEnd',
valueNumber: 'valueNumber',
phoneNumber: 'phoneNumber'
}];
let output = '';
function addButton() {
notificationList.forEach(item => {
output = `
<div class="container">
<div class="row">
<div class="col">
${item.email} - 1 of 2
</div>
<div class="col">
${item.typeNotification} - 2 of 2
</div>
</div>
<div class="row">
<div class="col">
${item.timeStart} - 1 of 3
</div>
<div class="col">
${item.timeEnd} - 2 of 3
</div>
<div class="col">
${item.delayLimit} - 3 of 3
</div>
</div>
</div>
`;
target.innerHTML += output
});
}
</script>
As you can see, you can adjust the output before you add it to the target.
I have made all the properties in notificationList strings to save time, but in your example, they would be made up of other elements on the page.
Here is a working example: https://jsfiddle.net/14o8n30u/6/
--EDIT--
Here is the same thing, but this time a table gets updated, using javascript builtin table functions:
<button onclick="addButton()">Add</button>
<table></table>
<script>
const
targetTable = document.querySelector('table'),
headerRow = targetTable.createTHead().insertRow(),
tableBody = targetTable.createTBody(),
notificationList = [];
headerRow.insertCell().textContent = 'Notification Type';
headerRow.insertCell().textContent = 'Email';
headerRow.insertCell().textContent = 'Delay Limit';
function addButton() {
while (tableBody.firstChild) {
tableBody.removeChild(tableBody.firstChild);
}
notificationList.push({
typeNotification: `Type${Math.floor(Math.random() * Math.floor(10))}`,
email: `Name${Math.floor(Math.random() * Math.floor(1000))}#test.com`,
delayLimit: `${Math.floor(Math.random() * Math.floor(100))} seconds`,
});
notificationList.forEach(item => {
const newRow = tableBody.insertRow(0);
newRow.insertCell().textContent = item.typeNotification;
newRow.insertCell().textContent = item.email;
newRow.insertCell().textContent = item.delayLimit;
});
}
</script>
On mine, I used random data for illustration purposes, but in yours the data will be built from elements on the page.
Note that you have to keep the notificationList outside the addButton, or it gets reset to an empty array each time the button is clicked.
When the page loads, the table head and body are populated.
Then when the addButton is clicked, the table body is emptied, then a new notification is added to the notificationList.
Then, inside the forEach, which loops over the notifications, all the notifications get their own row added at the top of the table (i.e. the entire table body is repopulated each time addButton is clicked).
You may not need to populate your own table header, but if you do, you can see how in this example.
Here it is working (I couldn't get it to work on jsfiddle for some reason): https://codepen.io/leonsegal/pen/oyKBQb
Hope that helps
var notificationListLength = notificationList.length;
var html_data = '';
for(var i = 0;i < notificationListLength;i++)
{
html_data += '<div class="container">
<div class="row">
<div class="col">
1 of 2
</div>
<div class="col">
2 of 2
</div>
</div>
<div class="row">
<div class="col">
1 of 3
</div>
<div class="col">
2 of 3
</div>
<div class="col">
3 of 3
</div>
</div>
</div>';
}
/* Make a div(id="html_div") when you need display data */
document.getElementById("html_div").innerHTML = html_data ;
I have problem with my code.
I have products on my website, each product has his own <a><h1>CODE</h1></a> and I need to take this CODE and paste it before an image. I need to copy element with has class="loop1" and paste it into another element with class="lop1" and then take another element with class="loop2" and paste into element with class="lop2" and so on..
I made class with same numbers for easier copying, but it doesnt work. Can sombody help me?
This is my code:
$('#loop').addClass(function(i) {
return 'lop'+(i+1);
});
$('.p-name').addClass(function(i) {
return 'loop'+(i+1);
});
function doForm() {
var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];
for (var i=0;i<numb.length;i++) {
number = numb[i];
selector = '.loop' + number;
if ($(selector).length != 0) {
val = $(selector).html();
$('lop' + number).html(val);
}
}
}
doForm();
Related html:
<div class="columns">
<div id="loop" class="lop1"></div>
<div class="p-image">
<img src="https://" width="290" height="218">
</div>
<div class="p-info">
<span itemprop="name">PRODUCT</span>
</div>
<div>
So I need to take from "p-info > a" and paste it into div "lop1". Depends on number in class copy and paste HTML into div with same number.
Change $('lop' + radek).html(val); to $('.lop' + number).html(val);
Notice the . at the beginning of lop, it will create a selector to fetch element based on the class.
$('#loop').addClass(function(i) {
return 'lop'+(i+1);
});
$('.p-name').addClass(function(i) {
return 'loop'+(i+1);
});
function doForm() {
var numb = ["1","2","3","4","5","6","7","8","9","10","11","13","14"];
for (var i=0;i<numb.length;i++) {
var number = numb[i];
var selector = '.loop' + number;
if ($(selector).length != 0) {
var val = $(selector).html();
$('.lop' + number).html(val);
}
}
}
doForm();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="columns">
<div id="loop" class="lop1"></div>
<div class="p-image">
<img src="https://" width="290" height="218">
</div>
<div class="p-info">
<span itemprop="name">PRODUCT</span>
</div>
<div>
Hi i'm building a project which has a page navigation and search bar in jQuery.
I can't get my search function to work correctly and I'm not certain if it's a problem with the ID element or the each function. I'm getting the ("Sorry, no student's found!") message for anything that is or isn't a match. So i think there could be a problem with the if statement looking for a match in search function--but not sure.
I'm dynamically adding a search box to my html like this:
function appendSearchBox(){
var search = "<div class='student-search'><input id='search' placeholder='Search for students...'><button>Search</button></div>"
$(".students").after(search);
// Add click event handler
$("button").click(function() {
searchList();
});
}
this is what my html looks like for a list of students:
<div class="page">
<div class="page-header cf">
<h2 class="students">Students</h2>
</div>
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
<h3>iboya vat</h3>
<span class="email">iboya.vat#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 07/15/15</span>
</div>
</li>
</ul>
And then here is the actual search function:
var listStudents = $(".student-list li");
var numStudents = listStudents.length;
function searchList() {
var matched = [];
// Obtain the value of the search input
input = $("#search").val()
// remove the previous page link section
$('.pagination').hide();
// Loop over the student list, and for each student…
listStudents.each(function(){
// ...obtain the student’s name…
var name = $(this).find("h3").val();
// ...and the student’s email…
var email = $(this).find(".email").val();
// ...if the search value is found inside either email or name…
if (name.includes(input) || email.includes(input)) {
// ...add this student to list of “matched” student
matched.push($(this).parent());
}
});
// If there’s no “matched” students…
if (matched.length === 0){
// ...display a “no student’s found” message
var message = ("Sorry, no student's found!");
$(".student-list").hide();
$(".student-list").after(message);
if (matched.length > 10) {
// ...call appendPageLinks with the matched students
appendPageLinks(matched);
}
// Call showPage to show first ten students of matched list
showPage(1, matched);
}
}
adding functions which actually show the students and add navigation
function showPage(pageNum, listStudents) {
// first hide all students on the page
pageNum = parseInt(pageNum);
listStudents.hide();
// Then loop through all students in our student list argument
listStudents.each(function(index){
// if student should be on this page number
if ((index >= ((pageNum*10)-9)) && (index <= (pageNum*10))) {
// show the student
$(this).show();
}
});
}
function getNumPages(numStudents){
numPages = Math.ceil(numStudents/10);
return numPages;
}
function appendPageLinks(numStudents) {
// determine how many pages for this student list
pages = getNumPages(numStudents);
// create a page link section
var nav = "<div class='pagination'><ul>"
for (i=1; i<pages+1; i+=1){
nav += ("<li>" + "" + i + "" + "</li>");
};
nav += ("</ul></div>");
$(".student-list").after(nav);
// define what happens when you click a link
var active = $('.pagination a').click(function(){
// Use the showPage function to display the page for the link clicked
var id = $(this).attr('id');
showPage(id,listStudents);
// mark that link as “active”
active.removeClass('active');
$(this).addClass("active");
});
}
here is how i am calling the functions:
appendSearchBox();
showPage(1, listStudents);
appendPageLinks(numStudents);
UPDATE -- I have changed the code to remove the val and put in to grab the text.
Not sure what issue is but it appears if i have a correct match--it is working (since pagination disappears) but the students do not change on the page. If there is no match then I get the error message, but the error console is saying
Uncaught TypeError: listStudents.hide is not a function
at showPage (main.js:8)
I'm not sure if this is somehow related to how I am passing the 'matched' list?
h3 and span tags have no value, but text content, so replace:
var name = $(this).find("h3").val();
// ...and the student’s email…
var email = $(this).find(".email").val();
with:
var name = $(this).find("h3").text();
// ...and the student’s email…
var email = $(this).find(".email").text();
You are using val() method to read inner text of h3 and span (email). It should be text(). Also you are appending message after the student list every time you couldn't find a student. You could have used one span tag and hide/show based on the search results.
function appendSearchBox() {
var search = "<div class='student-search'><input id='search' placeholder='Search for students...'><button>Search</button></div>"
$(".students").after(search);
// Add click event handler
$("button").click(function () {
searchList();
});
}
$(document).ready(function () {
appendSearchBox();
});
function searchList() {
var listStudents = $(".student-list li");
var numStudents = listStudents.length;
$(".student-list").show();
$("#message").hide();
var matched = [];
// Obtain the value of the search input
input = $("#search").val()
// remove the previous page link section
$('.pagination').hide();
// Loop over the student list, and for each student…
listStudents.each(function () {
// ...obtain the student’s name…
var name = $(this).find("h3").text();
// ...and the student’s email…
var email = $(this).find(".email").text();
// ...if the search value is found inside either email or name…
if (name.includes(input) || email.includes(input)) {
// ...add this student to list of “matched” student
matched.push($(this).parent());
}
});
// If there’s no “matched” students…
if (matched.length === 0) {
// ...display a “no student’s found” message
var message = ("Sorry, no student's found!");
$(".student-list").hide();
$("#message").show();
if (matched.length > 10) {
// ...call appendPageLinks with the matched students
appendPageLinks(matched);
}
// Call showPage to show first ten students of matched list
showPage(1, matched);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="page">
<div class="page-header cf">
<h2 class="students">Students</h2>
</div>
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
<h3>iboya vat</h3>
<span class="email">iboya.vat#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 07/15/15</span>
</div>
</li>
</ul>
<span id="message" style="display:none;"><br/>Sorry, no student's found!</span>
</div>
I'm trying to create a function where I click a button and I get content from a <div>. After, I need to divide the content. I mean, if this div has 10 children, I need to save 5 children in my var code1 and the other 5 in var code2. My problem is I'm not able to use html() function. My code looks like:
$(".pluscontrol").click(function(){
var id = $(this).attr("id");
var items=$(this).closest("table").parent().next().children('#'+id).children().length;
var middle = items / 2;
var code1="";
$(this).closest("table").parent().next().children('#'+id).html(
function(index,currentcontent){
if (index < middle )
code1 = code1 + currentcontent;
});
if ( $(".modal-body .row .sdiv").attr("id") == 1 )
$(".modal-body .row #1.sdiv").html(code1);
if ( $(".modal-body .row .sdiv").attr("id") == 2 )
$(".modal-body .row #2.sdiv").html("...");
});
As you can see, at first, I get the children lenght but I get all items.
I've checked this reference but it not helps too much
the var items is the number of items
Giving an argument to .html() makes it change the HTML of the selected elements. If you want to get the HTML, just call .html() with no argument.
To get the HTML of all the elements in a collection, use .map() to iterate, then combine them with .join().
var allChildren = $(".parent").children();
var middle = Math.floor(allChildren.length/2);
var code1 = allChildren.slice(0, middle).map(function(index, element) {
return element.innerHTML + " " + index;
}).get().join(' ');
var code2 = allChildren.slice(middle).map(function(index, element) {
return element.innerHTML + " " + (index + middle);
}).get().join(' ');
$("#out1").html(code1);
$("#out2").html(code2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
<div class="child">Test1</div>
<div class="child">Test2</div>
<div class="child">Test3</div>
<div class="child">Test4</div>
<div class="child">Test5</div>
<div class="child">Test6</div>
<div class="child">Test7</div>
<div class="child">Test8</div>
<div class="child">Test9</div>
<div class="child">Test10</div>
</div>
First group:
<div id="out1"></div>
Second group:
<div id="out2"></div>
You can use querySelectorAll which gives u a collection of child element. It also has a length function which you can call. If you want you can chain a foreach method to it. I have broken it down for clarity.
var children = document.querySelectorAll('.parent > div');
var midPoint = Math.round(children.length / 2);
var firstHalf = Array.prototype.slice.call(children,0,midPoint);
var secondHalf = Array.prototype.slice.call(children,midPoint);
firstHalf.forEach(function(elm){
console.log(elm.innerHTML);
});
<div class="parent">
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
<div class="child"><p>Test1</p></div>
</div>
I have the following html structur (endless):
<div class="wrapper">
<div class="content"> Its block 3
<div class="number">3</div>
</div>
</div>
<div class="wrapper">
<div class="content"> Its block 2
<div class="number">2</div>
</div>
</div>
I want to sort it by clicking a button like this:
<div class="wrapper">
<div class="content"> Its block 2 <--- new order
<div class="number">2</div> <--- new order
</div>
</div>
<div class="wrapper">
<div class="content"> Its block 3 <--- new order
<div class="number">3</div> <--- new order
</div>
</div>
... but with my script it doesn´t work (because of the same div class name, I think?). So, how can I sort this and toggle the sort by highest number and lowest number? Can anybody help me?
function sortHigh(a, b) {
var date1 = $(a).find(".content .number").text()
var date2 = $(b).find(".content .number").text();
return $(a).find(".content .number").text() > $(b).find(".content .number").text();
};
function sortLow(a, b) {
var date1 = $(a).find(".content .number").text()
var date2 = $(b).find(".content .number").text();
return $(a).find(".content .number").text() < $(b).find(".content .number").text();
};
//how to toggle?
$(function () {
$('.sort').click(function () {
$('.content').sort(sortHigh).appendTo('.wrapper');
}, function () {
$('.content').sort(sortLow).appendTo('.wrapper');
});
});
Thats my bad try: fiddle
try to change your code with this:-
var toggle="high";
//how to toggle?
$(function(){
$('.sort').click(function () {
if (toggle == "high") {
toggle = "low";
$('.list').html($('.list .wrapper').sort(sortLow));
} else {
toggle = "high"
$('.list').html($('.list .wrapper').sort(sortHigh));
}
});
});
Demo
Using jQuery, you can add the sort functionality as such:
jQuery.fn.sortDomElements = (function() {
return function(comparator) {
return Array.prototype.sort.call(this, comparator).each(function(i) {
this.parentNode.appendChild(this);
});
};
})();
var srtdesc = true;
$(function() {
$(".sort").click(function() {
srtdesc = !srtdesc;
$(".list").children().sortDomElements(function(a, b) {
if (srtdesc) {
return Number($(a).find('.number').text()) - Number($(b).find('.number').text());
} else {
return Number($(b).find('.number').text()) - Number($(a).find('.number').text());
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="sort">Sort-Button</button>
<div class="list">
<div class="wrapper">
<div class="content">Its block 3
<div class="number">3</div>
</div>
</div>
<div class="wrapper">
<div class="content">Its block 1
<div class="number">1</div>
</div>
</div>
<div class="wrapper">
<div class="content">Its block 2
<div class="number">2</div>
</div>
</div>
</div>
You have two issues with your code.
The first is that your sorts are sorting strings. return "2" > "3" for example.
The other issue is that the click function you're using isn't toggling correctly. I'm guessing you're familiar with the .hover() syntax which is why you've done it that way.
As you can see, I'm forcing sortHigh and sortLow to return Numbers. I've also done a sorting low/high check and toggle within the click function.
function sortHigh(a, b) {
var date1 = Number($(a).find(".number").text());
var date2 = Number($(b).find(".number").text());
return date1 > date2;
};
function sortLow(a, b) {
var date1 = Number($(a).find(".number").text());
var date2 = Number($(b).find(".number").text());
return date1 <= date2;
};
$(function(){
var sortHighCheck = null;
$('.sort').click(function(){
if (sortHighCheck === true) {
$('.wrapper').sort(sortLow).appendTo('.list')
sortHighCheck = false;
} else {
$('.wrapper').sort(sortHigh).appendTo('.list')
sortHighCheck = true;
}
});
});
Edit: Forgot to add the jsfiddle link
If you want to sort, you can add data-val attribute to each content div:
<div class="content" data-val="2"> Its block 2 <--- new order
and sort each wrapper div with this code:
jQuery("#sort").click( function() {
jQuery('.wrapper').sort(function (a, b) {
return jQuery(a).find('.content').data('val') - jQuery(b).find('.content').data('val');
}).each(function (_, container) {
jQuery(container).parent().append(container);
});
});