I'm trying to make a shopping cart with pure JS. I'm trying to dynamically create some divs with my products and buttons to increase/decrease/delete them, but I am stuck. Below is my function which is creating these divs:
function displayCart() {
let output = '';
for (let i in cart) {
output += '<div class="card card-body cartc">' + '<p>' +
'<span id="' + cart[i].name + '">' + cart[i].name + '</span>' +
'<button class="minus">-</button>' +
' ' + cart[i].count + ' шт.' +
'<button class="plus">+</button>' +
'<button class="delete">x</button>' +
'</p>' + '</div>';
};
document.querySelector('.cart').innerHTML = output;
document.querySelector('.total').innerHTML = totalCost();}
So the next step is to put events on buttons.
document.addEventListener("click", function (event) {
if (document.querySelector('.minus')) {
let name = this.querySelector('.cartc span').getAttribute("id");
removeItemFromCart(name);
displayCart();
}});
As you can see, it finds the first .cart span id and returns it to removeItemFromCart(), but this function should work in every div that I create, not just the first one. How can it be solved?
You can take a look at the whole project at https://enoltc.github.io/hw-2/ or https://github.com/ENoLTC/hw-2/
Creating a Shopping Cart using only HTML/JavaScript
The difference is that I want to write my script in pure JavaScript, without using simpleCart or jQuery.
So I did it this way
let buttons = document.getElementById("show-cart");
buttons.addEventListener("click", function (event) {
let name = event.target.getAttribute("data-name");
if (event.target.className === "delete") {
removeItemFromCartAll(name);
displayCart();
} else if (event.target.className === "minus") {
removeItemFromCart(name);
displayCart();
} else if (event.target.className === "plus") {
addItemToCart(name, 0, 1);
displayCart();
}
});
I have a list of tables.
var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
if (data[i].current_order == null) {
tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
} else {
tables += '<button class="table_selected" key="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
}
And tables have two color, when it is busy or not busy. If there is current_order in table, it shows busy. What I want to do is that when a user clicks empty table, it gets table_id, changes class from table_btn to table_selected and add keyof div, which is current_order.
I use phoenix-framework for my backend, so when a user clicks an empty table, it creates order and passes value of clicked table_id and created order_id. But I am not sure that how can I get a table by value of table div and put key into div...
Can anyone give me advice for this??
So as you tagged Jquery, i'm gonna post this. Change key for ID and you can do the following. I would then wrap the add table and remove table in functions where u pass in the data[i].current_order into and use that.
Edited based on user feeback, not tested
/*If you are not comfortable using the variable 'This',
you can just pass in the id of target table and
change the syntax to $("#"+targetTable)*/
var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
if (data[i].current_order == null) {
tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
} else {
tables += '<button class="table_selected" id="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
}
// On Click set table to busy
$(".table_btn").click(function(){
addTable($(this).val(), $(this));
});
// Add table function
function addTable(tableId, targetTable){
$.ajax({
url: "YourBackEndHere",
data: tableID
cache: false,
success: function(html){
$(targetTable).removeClass("table_btn");
$(targetTable).addClass("table_selected");
$(targetTable).attr("id", data[i].current_order);
}
});
}
// On click set table to empty
$(".table_selected").click(function(){
removeTable($(this).val(), $(this));
});
// Remove table function
function removeTable(tableId, targetTable){
$.ajax({
data: tableId
url: "YourBackEndHere",
cache: false,
success: function(html){
$(targetTable).removeClass("table_selected");
$(targetTable).addClass("table_btn");
$(targetTable).attr("id", "");
});
}
});
}
I have an application that allows users to select one or more courses. The user may choose to save the selected courses and come back later to finish the process. When/if the user returns, I recreate the list of checkboxes. Then, I try to find all the input checkboxes within that div. I log it to the console, and it returns an empty collection. How do I obtain the checkboxes properties?
The empty div that is populated with the checkboxes.
<div class="courseList applyBackgroundColor" id="UserCheckList">
</div>
Where I am doing the post and creating the dynamic textboxes using the result.
var createCourse = function(studentID)
{
var StudentCourseList = '<table><tbody>';
do post here
$.each(result, function (index, item) {
StudentCourseList += '<td valign="top" style="width:1%" id=td.ck.' +
item.ID + '><div class=""><input type="checkbox" class="checkbox"
id="'+ item.ID + '" value="' + item.ID + '" /></div></td>
<td valign="top" style="width:30%;padding:.25em;" id="' + item.ID +
'"><span id="span.' + item.ID + '" title="' + item.Description + '">'
+ item.Description +'</span></td>';
}
$('#UserCheckList').html(StudentCourseList );
}
Checking if there is a student id when the page loads.
$(function(){
var studentID = $('#studentID').val();
if(studentID !==''){
createCourse(studentID);
var listCheckUsers = $('.courseList').find('input[type=checkbox]');
console.log(listCheckUsers);
if I put a breakpoint next to listCheckUsers and debug it, the result that is displayed in the console is shown below:
Object[input#MAC201.checkbox attribute value = "MATH 201",
input#ENC101.checkbox attribute value = "ENGLISH 101",....]
}
without the breakpoint, I see an empty object
Object[]
});
Updated: Adding the exact JQuery message.
//This is shown when I do not use a breakpoint.
1. jQuery.fn.init[0]
1. context: document
2. length: 0
3. prevObject: jQuery.fn.init[1]
1. 0: div#UserCheckList.Display
2. context: document
3. length: 1
4. selector: "#UserCheckList"
5. __proto__: jQuery[0]
4. selector: "#UserCheckList input[type=checkbox]"
5. __proto__: jQuery[0]
You were missing the className courseList in the table element.
update
I simulated an Ajax request by using setTimeout. You can remove the setTimeout code and put an Ajax request in place. When the data is returned run your callback function with the data.
function getResults(studentID, callback) {
// Async call.
setTimeout(function() {
// Replace generator with Ajax call
var result = [];
for (var i = 0; i < 10; i++) {
var item = {
ID: i,
"Description": "Result #" + i
};
result.push(item);
}
// Run this when data returns.
callback(result);
}, 3000);
// Show loading while we wait.
$('.UserCheckList').html('loading...');
}
function showResults(result) {
var StudentCourseList = '<table class="courseList"><tbody>';
$.each(result, function(index, item) {
StudentCourseList += '<tr><td valign="top" style="width:1%" id=td.ck.' +
item.ID + '><div class=""><input type="checkbox" class="checkbox"\
id="' + item.ID + '" value="' + item.ID + '" /></div></td>\
<td valign="top" style="width:30%;padding:.25em;" id="' + item.ID +
'"><span id="span.' + item.ID + '" title="' + item.Description + '">' + item.Description + '</span></td></tr>';
});
$('.UserCheckList').html(StudentCourseList);
}
$(function() {
var studentID = $('#studentID').val();
if (studentID !== '') {
getResults(studentID, function(results) {
// callback when results are complete.
showResults(results);
var listCheckUsers = $('.courseList').find('input[type=checkbox]');
console.log(listCheckUsers);
});
}
}); //end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="UserCheckList"></div>
In one of the jsp pages of my project, I have this jquery code, which fill a table with dynamic data from server (the json strings):
$('document').ready(function(){
var obj_data = jQuery.parseJSON( '{"Data":[{"data":"2014-04-10","string":"10/MAR"},{"data":"2014-04-11","string":"11/MAR"},{"data":"2014-04-12","string":"12/MAR"},{"data":"2014-04-13","string":"13/MAR"},{"data":"2014-04-14","string":"14/MAR"},{"data":"2014-04-15","string":"15/MAR"},{"data":"2014-04-16","string":"16/MAR"},{"data":"2014-04-17","string":"17/MAR"},{"data":"2014-04-18","string":"18/MAR"},{"data":"2014-04-19","string":"19/MAR"}]}' );
var obj_hora = jQuery.parseJSON( '{"Hora":[{"hora":"04:30:00","string":"4:30-4:30"},{"hora":"05:00:00","string":"5:0-5:0"},{"hora":"05:30:00","string":"5:30-5:30"},{"hora":"06:00:00","string":"6:0-6:0"},{"hora":"06:30:00","string":"6:30-6:30"},{"hora":"07:00:00","string":"7:0-7:0"},{"hora":"07:30:00","string":"7:30-7:30"},{"hora":"08:00:00","string":"8:0-8:0"},{"hora":"08:30:00","string":"8:30-8:30"},{"hora":"09:00:00","string":"9:0-9:0"},{"hora":"09:30:00","string":"9:30-9:30"},{"hora":"10:00:00","string":"10:0-10:0"}]}' );
var obj_horario = jQuery.parseJSON( '{"Horario":[{"horario":"2014-04-11 06:00:00","data":"2014-04-11","string_data":"11/MAR","hora":"06:00:00","string_hora":"6:0-6:0"},{"horario":"2014-04-11 06:30:00","data":"2014-04-11","string_data":"11/MAR","hora":"06:30:00","string_hora":"6:30-6:30"},{"horario":"2014-04-11 07:00:00","data":"2014-04-11","string_data":"11/MAR","hora":"07:00:00","string_hora":"7:0-7:0"},{"horario":"2014-04-12 06:00:00","data":"2014-04-12","string_data":"12/MAR","hora":"06:00:00","string_hora":"6:0-6:0"},{"horario":"2014-04-12 06:30:00","data":"2014-04-12","string_data":"12/MAR","hora":"06:30:00","string_hora":"6:30-6:30"},{"horario":"2014-04-12 07:00:00","data":"2014-04-12","string_data":"12/MAR","hora":"07:00:00","string_hora":"7:0-7:0"},{"horario":"2014-04-13 06:00:00","data":"2014-04-13","string_data":"13/MAR","hora":"06:00:00","string_hora":"6:0-6:0"},{"horario":"2014-04-13 06:30:00","data":"2014-04-13","string_data":"13/MAR","hora":"06:30:00","string_hora":"6:30-6:30"},{"horario":"2014-04-13 07:00:00","data":"2014-04-13","string_data":"13/MAR","hora":"07:00:00","string_hora":"7:0-7:0"},{"horario":"2014-04-14 06:00:00","data":"2014-04-14","string_data":"14/MAR","hora":"06:00:00","string_hora":"6:0-6:0"},{"horario":"2014-04-14 06:30:00","data":"2014-04-14","string_data":"14/MAR","hora":"06:30:00","string_hora":"6:30-6:30"},{"horario":"2014-04-14 07:00:00","data":"2014-04-14","string_data":"14/MAR","hora":"07:00:00","string_hora":"7:0-7:0"},{"horario":"2014-04-15 06:00:00","data":"2014-04-15","string_data":"15/MAR","hora":"06:00:00","string_hora":"6:0-6:0"},{"horario":"2014-04-15 06:30:00","data":"2014-04-15","string_data":"15/MAR","hora":"06:30:00","string_hora":"6:30-6:30"},{"horario":"2014-04-15 07:00:00","data":"2014-04-15","string_data":"15/MAR","hora":"07:00:00","string_hora":"7:0-7:0"},{"horario":"2014-04-16 06:00:00","data":"2014-04-16","string_data":"16/MAR","hora":"06:00:00","string_hora":"6:0-6:0"},{"horario":"2014-04-16 06:30:00","data":"2014-04-16","string_data":"16/MAR","hora":"06:30:00","string_hora":"6:30-6:30"},{"horario":"2014-04-16 07:00:00","data":"2014-04-16","string_data":"16/MAR","hora":"07:00:00","string_hora":"7:0-7:0"},{"horario":"2014-04-17 06:00:00","data":"2014-04-17","string_data":"17/MAR","hora":"06:00:00","string_hora":"6:0-6:0"},{"horario":"2014-04-17 06:30:00","data":"2014-04-17","string_data":"17/MAR","hora":"06:30:00","string_hora":"6:30-6:30"},{"horario":"2014-04-17 07:00:00","data":"2014-04-17","string_data":"17/MAR","hora":"07:00:00","string_hora":"7:0-7:0"},{"horario":"2014-04-18 06:00:00","data":"2014-04-18","string_data":"18/MAR","hora":"06:00:00","string_hora":"6:0-6:0"},{"horario":"2014-04-18 06:30:00","data":"2014-04-18","string_data":"18/MAR","hora":"06:30:00","string_hora":"6:30-6:30"},{"horario":"2014-04-18 07:00:00","data":"2014-04-18","string_data":"18/MAR","hora":"07:00:00","string_hora":"7:0-7:0"}]}' );
var newRow1 = $('<tr>');
for(var item in obj_hora.Hora) {
newCol1 = "<td></td>";
for(var item2 in obj_data.Data) {
newCol1 += '<td>' + obj_data.Data[item2].string + '</td>';
}
}
newRow1.append(newCol1);
$("table.horarios").append(newRow1);
var counter = 1;
var newRow2 = "";
for(var item in obj_hora.Hora) {
newRow2 = $('<tr>');
newCol2 = '<td>' + obj_hora.Hora[item].string + '</td>';
for(var item2 in obj_data.Data) {
newCol2 += '<td>' + '<input type="checkbox" class="horario" data-key_data="'+obj_data.Data[item2].data+'" data-key_hora="'+obj_hora.Hora[item].hora+'" name="'+counter+'">' + '</td>';
for(var index in obj_horario.Horario) {
if(obj_hora.Hora[item].hora == obj_horario.Horario[index].hora && obj_data.Data[item2].data == obj_horario.Horario[index].data)
$('input[name='+counter+']').attr("checked", "true");
}
counter++;
}
newRow2.append(newCol2);
$("table.horarios").append(newRow2);
}
});
My problem is with this line:
for(var index in obj_horario.Horario) {
if(obj_hora.Hora[item].hora == obj_horario.Horario[index].hora && obj_data.Data[item2].data == obj_horario.Horario[index].data)
$('input[name='+counter+']').attr("checked", "true");
}
that line should make the checkbox with similar values of date and time checked, but when I run the application and open this page, nothing is checked, despite I have data in the variable 'obj_horario', as you can see in the code above.
Someone can see what i am doing wrong here?
UPDATE
I change the code highlight above to this:
for(var index in obj_horario.Horario) {
if(obj_hora.Hora[item].hora == obj_horario.Horario[index].hora && obj_data.Data[item2].data == obj_horario.Horario[index].data) {
console.info('counter='+counter);
console.info('Hora = ' + obj_hora.Hora[item].hora + '| Horario.hora = ' + obj_horario.Horario[index].hora);
console.info('Data = ' + obj_data.Data[item2].data + '| Horario.data = ' + obj_horario.Horario[index].data);
var checkbox = $('input[name='+counter+']');
$(checkbox).attr("checked", "true");
}
}
to include the console.info() function; now, i can see in the browser console that the itens which should be checked are being selected correctly by the if sentence, but i guess this snippet of the code:
var checkbox = $('input[name='+counter+']');
$(checkbox).attr("checked", "true");
aren't working properly. My guess it's because it is referring a dynamically created object - I have a similar problem before, and solve including the dynamic object inside a static one, and binding an event to this static element, but now I can't figure out how to do the same, since I'm triggering any event, just are adding the element to the page.
Anyone can point me a direction for solving this?
In this part:
for(var item in obj_hora.Hora) {
newRow2 = $('<tr>');
newCol2 = '<td>' + obj_hora.Hora[item].string + '</td>';
for(var item2 in obj_data.Data) {
newCol2 += '<td>' + '<input type="checkbox" class="horario" data-key_data="'+obj_data.Data[item2].data+'" data-key_hora="'+obj_hora.Hora[item].hora+'" name="'+counter+'">' + '</td>';
for(var index in obj_horario.Horario) {
if(obj_hora.Hora[item].hora == obj_horario.Horario[index].hora && obj_data.Data[item2].data == obj_horario.Horario[index].data)
$('input[name='+counter+']').attr("checked", "true");
}
counter++;
}
newRow2.append(newCol2);
$("table.horarios").append(newRow2);
}
you are not appending newCol2 to the DOM (with .append()) until the end of the for loop. As a result, within the for loop, where your $('input [name='+counter+']') gets executed, there is not (yet) such an element within the DOM.
Possible solutions:
(1st solution) Add this for loop after your .append() (so after the code snippet you pasted):
for(var item in obj_hora.Hora) {
for(var item2 in obj_data.Data) {
for(var index in obj_horario.Horario) {
if(obj_hora.Hora[item].hora == obj_horario.Horario[index].hora && obj_data.Data[item2].data == obj_horario.Horario[index].data)
$('input[name='+counter+']').attr("checked", "true");
}
counter++;
}
}
(2nd solution) Replace your original code with something like this:
for(var item in obj_hora.Hora) {
newRow2 = $('<tr>');
newCol2 = '<td>' + obj_hora.Hora[item].string + '</td>';
newRow2.append(newCol2);
for(var item2 in obj_data.Data) {
newCol2 = '<td>' + '<input type="checkbox" class="horario" data-key_data="'+obj_data.Data[item2].data+'" data-key_hora="'+obj_hora.Hora[item].hora+'" name="'+counter+'">' + '</td>';
newRow2.append(newCol2);
for(var index in obj_horario.Horario) {
if(obj_hora.Hora[item].hora == obj_horario.Horario[index].hora && obj_data.Data[item2].data == obj_horario.Horario[index].data)
$('input[name='+counter+']').attr("checked", "true");
}
counter++;
}
$("table.horarios").append(newRow2);
}
I have the following code:
remove: function(child, obj){
for (var i = 0, len = obj.compareComponents.length; i < len; i++) {
if (obj.compareComponents[i] == child) {
obj.compareComponents.splice(i, 1);
break;
}
}
dojo.forEach(obj.checks, function(arr){
if (arr.number == child.id) {
obj.states.checkMarks.empty(arr, obj, child);
}
});
obj.properties.numberTaken--;
obj.states.compare.checksFull.value.isTrue = false;
obj.states.compare.checksFull.settings(obj);
if (obj.properties.numberTaken < 2) {
obj.states.compare.noChecks(obj);
}
}
What I am trying to as the checkboxes are unchecked and removed I want the focus to be set on the element to the right of it. What logic do I add to accomplish this?
Focus will set automatically if I can set the tab index of the first checkbox to 0 here is the code that was written creating the check boxes how would I modify it to set the first element's tab index to 0?
var image = arr.image[0].src;
image = '<th id="cell4' + arr.id + '" scope="col"><span class="pcChecks"><input checked="checked" type="checkbox" name="pc' + arr.id + '" id="pc' + arr.id + '" class="compare" /><label for="pc' + arr.id + '" id="" class="compare">' + '<span class="hide-fromsighted">Remove ' + temptitle + '</span>' + 'Remove</label></span><div><img height="106" alt="' + temptitle + '"src="' + image + '"/></div></th>'
If all your checkboxes are the children of the same parent, then in jQuery, I'd use $(obj).next().focus().
I couldn't find a similar API in dojo :-( Which means you'll have to get the children, search yourself and then select the child with index+1.