function makeUL() {
var products = JSON.parse(localStorage["products"]);
var list = document.createElement('ul');
for(var i = 0; i < products.length; i++) {
if(products[i].amount == 0) {
continue;
}
// Create the list item:
var item = document.createElement('li');
var product = products[i];
var totalPrice = product.amount * product.price;
var toDisplay = product.name + " " + product.amount + " #" + totalPrice + " ";
// Set its contents:
item.appendChild(document.createTextNode(toDisplay));
var inputbox = document.createElement("input");
inputbox.setAttribute("id", "inputboxProduct" + i);
inputbox.addEventListener("change", function(){
changeAmountProd(inputbox.id);
});
item.appendChild(inputbox);
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
This will basically make a list when you hover over a certain string. The list will be based on the localstorage and make an inputbox for each point of that list.
The problem is the adding of eventlisteners. For some reason it always returns an empty value when the event is triggered of that inputbox.
function changeAmountProd(inputboxId) {
var products = JSON.parse(localStorage["products"]);
value = document.getElementById(inputboxId).value;
if(value < 1) {
return;
}
products[i].amount = value;
localStorage["products"] = JSON.stringify(products);
makeUL();
}
The problem is with the callback of your change event. You're referring to the changed element using the inputbox variable (that is available through the closure) but by the time your callback is invoked, inputbox will always point to the last generated element.
Try this instead:
inputbox.addEventListener("change", function(){
changeAmountProd(this.id);
});
See addEventListener
Try this:
function makeUL() {
var products = JSON.parse(localStorage["products"]);
var list = document.createElement('ul');
for(var i = 0; i < products.length; i++) {
if(products[i].amount == 0) {
continue;
}
// Create the list item:
var item = document.createElement('li');
var product = products[i];
var totalPrice = product.amount * product.price;
var toDisplay = product.name + " " + product.amount + " #" + totalPrice + " ";
// Set its contents:
item.appendChild(document.createTextNode(toDisplay));
var inputbox = document.createElement("input");
inputbox.setAttribute("id", "inputboxProduct" + i);
inputbox.addEventListener("change", function(){
changeAmountProd(this.id);
});
item.appendChild(inputbox);
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
Related
I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you
I have created an accordion with categories. I am pulling the content from a share point list with an ajax call. Each item on the share point list has its category assigned (automotive, entertainment, housing, etc). I need every item to be filtered by category.
https://jsfiddle.net/angelogianopulos/7L392emj/11/
$(document).ready(function() {
/*r container = document.createElement("div");
container.setAttribute('id', 'container');
container.classList.add('container', 'text-center', 'my-5');*/
$.ajax({
url: "http://bc-net/_api/web/lists/GetByTitle('specialDiscounts')/items",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
var items = data.d.results;
console.log(items);
var createRows = function(i, items) {
//Creates 3 Rows inside container
var row = document.createElement("div");
row.setAttribute('id', 'row' + i);
row.classList.add('row', 'animated', 'fadeInUp');
//Appends Row to Container
var getContainer = document.getElementById('automotive');
getContainer.appendChild(row);
createColumns(i, items);
}; //End of creare Rows Function
//Creates columns
var createColumns = function(i, items) {
for (var j = i; j < (i + 3); j++) {
//Creates 3 Columns inside the 3 rows
var columns = document.createElement("div");
columns.setAttribute('id', 'columns' + j);
columns.classList.add('col-md-4');
//appends the 3 columns inside the rows
var getRow = document.getElementById('row' + i);
getRow.appendChild(columns);
//Create single News
var singleNews = document.createElement("div");
singleNews.setAttribute('id', 'singleNews' + j);
singleNews.classList.add("single-news", "mb-4");
var getColumns = document.getElementById('columns' + j);
getColumns.appendChild(singleNews);
//Inside Row
var insideRow = document.createElement("div");
insideRow.setAttribute('id', 'insideRow' + j);
insideRow.classList.add('row');
var getsingleNews = document.getElementById('singleNews' + j);
getsingleNews.appendChild(insideRow);
//Col-md-3
var insideCol = document.createElement("div");
insideCol.setAttribute('id', 'insideCol' + j);
insideCol.classList.add('col-md-3');
//Col-md-9
var insideColRight = document.createElement("div");
insideColRight.setAttribute('id', 'insideColRight' + j);
insideColRight.classList.add('col-md-9');
var getInsideRow = document.getElementById('insideRow' + j);
getInsideRow.appendChild(insideCol);
getInsideRow.appendChild(insideColRight);
//Rounded Image Class
var rounded = document.createElement("div");
rounded.setAttribute('id', 'rounded' + j);
rounded.classList.add('rounded', 'z-depth-1', 'mb-4');
var getinsideCol = document.getElementById('insideCol' + j);
getinsideCol.appendChild(rounded);
//Pulls the images from the list
var image = document.createElement("img");
image.setAttribute('id', 'image' + j);
image.classList.add("img-fluid");
image.src = items[j].Image.Url;
var getRounded = document.getElementById('rounded' + j);
getRounded.appendChild(image);
//Pulls header from the list
var title = document.createElement("p");
title.setAttribute('id', 'title' + j);
title.innerHTML = items[j].Title;
title.classList.add("font-weight-bold", "dark-grey-text");
insideColRight.appendChild(title);
var justifyContent = document.createElement('div');
justifyContent.setAttribute('id', 'justifyContent' + j);
justifyContent.classList.add('d-flex', 'justify-content-between', 'topSpace');
insideColRight.appendChild(justifyContent);
var textTruncate = document.createElement('div');
textTruncate.setAttribute('id', 'textTruncate' + j);
textTruncate.classList.add('col-11', 'text-truncate', 'pl-0', 'mb-3');
justifyContent.appendChild(textTruncate);
//Pulls anchor from the list
var anchor = document.createElement("a");
anchor.setAttribute('id', 'anchor' + j);
anchor.setAttribute('href', items[j].Link.Url, +j);
anchor.setAttribute('target', '_blank', +j);
anchor.classList.add("dark-grey-text");
anchor.innerHTML = items[j].Description;
textTruncate.appendChild(anchor);
var arrowAnchor = document.createElement("a");
arrowAnchor.setAttribute('id', 'arrowAnchor' + j);
arrowAnchor.setAttribute('target', '_blank' + j);
arrowAnchor.setAttribute('href', items[j].Link.Url, +j);
justifyContent.appendChild(arrowAnchor);
var iconArrow = document.createElement('i');
iconArrow.classList.add('fas', 'fa-angle-double-right');
var getarrowAnchor = document.getElementById('arrowAnchor' + j);
getarrowAnchor.appendChild(iconArrow);
//var test = document.getElementById( 'arrowAnchor' + j);
//test.onclick = function() {
// console.log('Hello');
//}
} //End of j Loop
return;
} // End of createColumns function
//Array of categories
var catGroup = [];
console.log(catGroup);
if (items.length > 0) {
for (var i = 0; i < items.length; i++) {
var categories = items[i].Category;
console.log(categories)
catGroup.push(categories);
if (catGroup[i] === "Automotive") {
var automotive = document.getElementById('automotive');
console.log(catGroup[i]);
}
if (catGroup[i] === "Entertainment") {
var entertainment = document.getElementById('entertainment');
console.log(catGroup[i]);
}
if (catGroup[i] === "Health and Beauty") {
var health = document.getElementById('health');
console.log(catGroup[i]);
}
if (catGroup[i] === "Travel") {
var travel = document.getElementById('travel');
console.log(catGroup[i]);
}
if (catGroup[i] === "Electronics") {
var electronics = document.getElementById('electronics');
console.log(catGroup[i]);
}
if (catGroup[i] === "Services") {
var services = document.getElementById('services');
console.log(catGroup[i]);
}
if (catGroup[i] === "Housing") {
var housing = document.getElementById('housing');
console.log(catGroup[i]);
} else {}
if (i % 3 == 0) {
createRows(i, items);
} //end of % if statement
} //End of for loop
} //End of if item.length statement
},
error: function(data) {
alert("Error: " + data);
}
}); //End Service Icons //End Service Icons
}); //End ready function
I expect every item to be placed by category in its own content panelenter image description here
After looking into your question, what I understood is you just want to filter your data on the basis of 'category assigned'.
I will refer you to use JavaScript Filter like so:
const result = items.filter(Category => Category === "Automotive" );
Or, if you can use Lodash, there are a lot of ways to filter and even you can group by the Category.
You can check out here for Lodash:
Documentation Lodash
If I misunderstood your question, please let me know so I can edit my answer.
I'm using JavaScript to remove, order up, order down a text row, it runs normally in IE, but not in Chrome or Firefox.
When I run, I received a message from console bug:
Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.
How to fix the error?
function dels(index) {
var frm = document.writeForm;
var opts = frm['ans' + index].value = ''; // eval("frm.ans_list" + index + ".options");
for (var i = 0; i < opts.length; i++) {
if (opts[i].selected) {
opts[i--].removeChild(true);
}
}
eval("frm.ans" + index + ".value = '' ");
setting_val(index);
}
function up_move(index) {
var frm = document.writeForm;
var opts = eval("frm.ans_list" + index + ".options"); // frm['ans' + index].value = '';
for (var i = 0; i < opts.length; i++) {
if (opts[i].selected && i > 0) {
tmp = opts[i].cloneNode(true);
opts[i].removeChild(true);
opts[i - 1].insertAdjacentElement("beforeBegin", tmp).selected = true;
}
}
setting_val(index);
}
**(UPDATED)**
function down_move(index)
{
var frm = document.writeForm;
var opts=frm["ans_list" + index].options // eval("frm.ans_list" + index + ".options"); // frm['ans' + index].value = '';
for (var i=opts.length-1; i>=0; i--) {
if (opts[i].selected && i<opts.length-1) {
tmp = opts[i].cloneNode(true);
opts[i].removeChild(true);
opts[i].insertAdjacentElement("afterEnd", tmp).selected = true;
}
}
setting_val(index);
}
<span class="bt_test_admin bg_type_01">Delete</span>
<span class="bt_test_admin bg_type_01">▲ Order</span>
<span class="bt_test_admin bg_type_01">▼ Order</span>
Wrong use of removeChild
if (opts[i].selected) {
opts[i--].removeChild(true);
}
The function is intended as:
ParentNode.removeChild(ChildNode);
// OR
ChildNode.parentNode.removeChild(ChildNode);
MDN Documentation on removeChild
Also, you can replace all your evals
eval("frm.ans" + index + ".value = '' ")
eval("frm.ans_list" + index + ".options")
It would be better written as
frm["ans" + index].value = ""
frm["ans_list" + index].options
Finally,
tmp = opts[i].cloneNode(true);
opts[i].removeChild(true);
opts[i].insertAdjacentElement("afterEnd", tmp).selected = true;
Cloning a node, appending the clone, and removing the original would be optimized as moving the original to its new location.
But, you try to remove the original, then insert the clone after the original. It's odd.
If I correctly understood what you try to do, this function could help you.
function reverse_options_order(select_element)
{
// we store the current value to restore it after reordering
const selected_value = select_element.value;
// document fragment will temporarily hold the children
const fragment = document.createDocumentFragment();
while (select_element.lastChild)
{
// last child become first child, effectively reversing the order
fragment.appendChild(select_element.lastChild);
}
// appending a fragment is equal to appending all its children
// the fragment will "merge" with the select_element seamlessly
select_element.appendChild(fragment);
select_element.value = selected_value;
}
You can use the same method to reverse any nodes order
I am trying to call two functions when only the "add" button is clicked. the problem I am having is that the final four textboxes in the calculate_balances function are not outputting their variables.
var $ = function (id) {
return document.getElementById(id);
}
// Declare Arrays to store information from Inputs //
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount
// Function to print results to text area //
var update_results = function () {
var list = ""; // string variable to build output //
// check to see if arrays are empty //
if (transactions[0].length == 0) {
$("results").value = "";
} else {
list = "";
// for loop to cycle through arrays and build string for textarea output //
for (var i = 0; i < transactions[0].length; i++) {
list += transactions[0][i] + " " + transactions[1][i] + " " + transactions[2][i] + "\n";
}
// display results //
$("results").value = list;
}
}
// function to gather inputs //
var add_transaction = function () {
$("add").blur();
transactions[0][transactions[0].length] = $("date").value;
transactions[1][transactions[1].length] = $("transType").value;
transactions[2][transactions[2].length] = parseFloat( $("amount").value);
update_results();
calculate_balances();
}
// function for Calculations //
var calculate_balances = function () {
var startBal = 2000.00;
var ttlDeposits = 0;
var ttlWithdrawals = 0;
var endBal = startBal;
if (transactions[1][transactions[1].length] == "deposit")
{
ttlDeposits += transactions[2][transactions[2].length];
endBal += ttlDeposits;
}
if (transactions[1][i] == "withdrawal")
{
ttlWithdrawals += transactions[2][transactions[i]];
endBal -= ttlWithdrawals;
}
$("balStart").value = parseFloat(startBal);
$("ttlDeposits").value = parseFloat(ttlDeposits);
$("ttlWithdrawals").value = parseFloat(ttlWithdrawals);
$("balEnd").value = parseFloat(endBal);
}
window.onload = function () {
$("add").onclick = add_transaction, calculate_balances;
update_results();
}
tHank you
Edit: Did not realize the OP was NOT using jQuery. Your onclick should look like this:
$("add").onclick = function(){
add_transaction();
calculate_balances();
};
The rest here is for jQuery which is not what the OP wanted.
For setting the value of a text box with jQuery use the val() method:
$("balStart").val(parseFloat(startBal));
To call the two methods when the button is clicked:
$("add").click(function(){
add_transaction();
calculate_balances();
});
I am trying to make a debugger that will be dynamiaclly created with some variables. The names on the left div need to show a div for the corresponding variables Description,Variable ID, and initial Value as well as another div that will show history and lock status when variables are updated later. Where I am having trouble is properly adding the show/hide to the dom I think. Everything starts hidden and then when I click a name the Variables for that name show up but the next click doesn't hide the values from the former. Also any cleanup/optimization advice?
<script type="text/javascript">
var variableIDArray = {};
function loadVariables(variables) {
if (typeof variables != "object") { alert(variables); return; }
var namearea = document.getElementById('namearea');
var description = document.getElementById('description');
var varid = document.getElementById('varid');
var initialvalue = document.getElementById('initialvalue');
var valuelock = document.getElementById('valuelock');
for (var i = 0; i < variables.length - 1; i++) {
var nameDiv = document.createElement('div');
nameDiv.id = variables[i].variableID + "namearea";
nameDiv.className = "nameDiv";
nameDiv.onclick = (function (varid) {
return function () { showvariable(varid); };
})(variables[i].variableID);
nameDiv.appendChild(document.createTextNode(variables[i].name));
namearea.appendChild(nameDiv);
var descriptionDiv = document.createElement('div');
descriptionDiv.id = variables[i].variableID + "description";
descriptionDiv.className = "descriptionDiv";
descriptionDiv.appendChild(document.createTextNode("Description : " + variables[i].description));
description.appendChild(descriptionDiv);
var varidDiv = document.createElement('div');
varidDiv.id = variables[i].variableID + "varid";
varidDiv.className = "varidDiv";
varidDiv.appendChild(document.createTextNode("Var ID : " + variables[i].variableID));
varid.appendChild(varidDiv);
var initialvalueDiv = document.createElement('div'); ;
initialvalueDiv.id = variables[i].variableID + "initialvalue";
initialvalueDiv.className = "initialvalueDiv";
initialvalueDiv.appendChild(document.createTextNode("Initial Value : " + variables[i].value));
initialvalue.appendChild(initialvalueDiv);
var valuelockDiv = document.createElement('div');
valuelockDiv.id = variables[i].variableID + "valuelock";
valuelockDiv.className = "valuelockDiv ";
valuelockDiv.appendChild(document.createTextNode("Value : " + variables[i].value));
valuelockDiv.appendChild(document.createTextNode("Lock : " + variables[i].locked.toString()));
valuelock.appendChild(valuelockDiv);
variableIDArray[variables[i].variableID];
}
};
function showvariable(varid) {
for (v in variableIDArray)
hide(variableIDArray[v]);
show(varid + "description");
show(varid + "varid");
show(varid + "initialvalue");
show(varid + "valuelock");
}
function show(elemid) {
document.getElementById(elemid).style.display = "block";
}
function hide(elemid) {
document.getElementById(elemid).style.display = "none";
}
Yes. jQuery. Will reduce your code to about 6 lines. :) http://jquery.com