Display data in a table from localStorage without repeating - javascript

I am making a shopping list in my web page where I add the items which I store in localStorage.The items are displayed in a table.The problem is that for each new item added it is showing also the data previously stored again.
My html is:
<form class="market">
<label>Nume produs</label>
<input type="text" id="np">
<label>Cantitate</label>
<input type="text" id="cp">
<input type="button" onclick="addItem();" id="adauga" value="Adaugă" />
</form>
<table>
<tbody id="shopping">
<tr>
<th>Nr.</th>
<th>Name</th>
<th>Quantity</th>
</tr>
And this is the function called on every button click
class Produs{
constructor(id, nume, cantitate){
this.id = id;
this.nume = nume;
this.cantitate = cantitate;
}
}
function addItem(){
let nume = document.getElementById("np").value;
let cantitate = document.getElementById("cp").value;
let produse = localStorage.getItem('produse');
if(produse == null){
produse = [];
}
else{
produse = JSON.parse(produse);
}
produse = produse.map((p) => {
return new Produs(p.id, p.nume, p.cantitate);
});
let lastId = localStorage.getItem('lastId');
if(lastId == null)
{
lastId=1;
}
else{
lastId = JSON.parse(lastId);
}
let id = lastId;
produse.push(new Produs(id, nume, cantitate));
localStorage.setItem('produse',JSON.stringify(produse));
localStorage.setItem('lastId',JSON.stringify(lastId+1));
var jsonData = JSON.parse(localStorage.getItem('produse'));
console.log(jsonData);
for(var i=0; i<jsonData.length; i++)
{
document.getElementById("shopping").innerHTML +="<tr><td>"+jsonData[i].id +"</td><td>" + jsonData[i].nume +"</td><td>"+jsonData[i].cantitate+"</td></tr>";
}
}

Related

Why does the method of adding goods work incorrectly?

When the listener "buttAdd.addEventListener" for the add method is triggered: , first this condition works several times(works with the second addition):
if (inputsAdd [0].value ===""||inputsAdd [1].value ===""||inputsAdd [2]
.value === "")
{alert ("fill all fields");}
It works when the fields are not empty, and then the product is added. And if you click on the add button with empty fields, then the product that was added earlier - will be lost. The same story awith the method, delete. Help me please to fix it
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
Product.SORT_ORDER_ASC = 1;
Product.SORT_ORDER_DESC = -1;
// Сlass where products are recorded
class Shop {
constructor() {
this.products = [];
this.formAdd = document.forms[0];
this.inputsAdd = this.formAdd.elements;
this.buttAdd = this.formAdd.elements[3];
this.formDelete = document.forms[1];
this.nameDelete = this.formDelete.elements[0];
this.buttDelete = this.formDelete.elements[1];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
// get total price by all products
get totalProductsPrice() {
return this.products.map(product => product.price).reduce((p, c) => p + c);
}
//method for sorting the product at its price
sortProductsByPrice(sortOrder) {
const sorted = this.products.sort((a, b) => {
return a.price > b.price ? sortOrder : -sortOrder;
});
this.products = sorted;
}
// method to draw the table with product property (
// name, count, price)
show() {
// add new product by click
this.buttAdd.addEventListener('click', (e) => {
e.preventDefault();
if (this.inputsAdd[0].value === "" || this.inputsAdd[1].value === "" || this.inputsAdd[2].value === "") {
alert("fill all fields");
} else {
this.addProduct(new Product(this.inputsAdd[0].value, parseInt(this.inputsAdd[2].value),
parseInt(this.inputsAdd[1].value)));
this.show();
this.inputsAdd[0].value = "";
this.inputsAdd[1].value = "";
this.inputsAdd[2].value = "";
}
}, false);
// delete product by name after click
this.buttDelete.addEventListener('click', (e) => {
e.preventDefault();
if (this.nameDelete.value === "") {
alert("write a name of product what you want to delete");
} else {
this.deleteProductByName(this.nameDelete.value);
this.show();
this.nameDelete.value = "";
}
}, false);
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
const tFoot = table.querySelector('tfoot');
if (tFoot) tFoot.remove();
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tbody><tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr></tbody>`;
}
//show total price by all products
table.innerHTML += `<tfoot><tr><td colspan="3" id="total-price">Total price:
${this.totalProductsPrice}</td></tr></tfoot>`;
//filter products by price
document.addEventListener("click", (e) => {
let elem = e.target;
if (elem.id === "filter") {
this.sortProductsByPrice(Product.SORT_ORDER_ASC);
this.show();
}
}, false);
console.log(this.products);
}
}
let shop = new Shop();
shop.addProduct(new Product("product", 1, 2000));
shop.addProduct(new Product("product1", 2, 500));
shop.addProduct(new Product("product2", 3, 1000));
shop.show();
<div class="Shop">
<div class="add-product">
<h1>Add product</h1>
<form id="addForm">
<label for="name" >Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add" type="button">Add</button><!-- *** -->
</form>
</div>
<div class="product-table">
<h2>Products</h2>
<form id="delete-form">
<label for="name-delete">Delete product by name</label>
<input type="text" id="name-delete" class="input-delete">
<button id="delete" type="button">Delete</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>
</div>
</div>
See, you're defining let shop = new Shop() and then use this variable in your Shop class, like shop.show(). I strongly recommend you to use this keyword instead of scoped variable (valid for all other shop usage entries).
Now, about
works several times
I assume, that when you call the show() method it registers more event listeners some time. I mean, you call show - it creates new event listeners + sometimes calls itself (huh, it is pretty risky). I suggest you to move listeners declaration to the constructor - so they will be instantinated once (but that will require keeping DOM nodes). Also it would be nice to split your show fucntion to several smaller functions and get rid of self function emit (it will reduce complexity).

Why wont my jsp page show all the objects from my angularjs list in ng-repeat?

JSP
<table class="countrys" data-name="tableProductsBuy">
<tr bgcolor="lightgrey">
<th>Product ID</th>
<th>Product Name</th>
<th>In Store</th>
</tr>
<tr data-ng-repeat="p in finalList"
data-ng-click="selectObject(p, $index);"
data-ng-class="getSelectedObject(p);">
<td>{{p.product.productId}}</td>
<td>{{p.product.productName}}</td>
<td>{{p.unitsOutStore}}</td>
</tr>
</table>
<button data-ng-click="buyIt()">Add to Shopping Cart</button>
controller
$scope.getSelectedObject = function(object) {
if ($scope.selectedObject.product.productId != undefined) {
if ($scope.selectedObject.product.productId == object.product.productId) {
return "selected";
}
}
return "";
};
$scope.selectObject = function(object, index){
$scope.selectedObject = object;
}
$scope.finalList = [];
$scope.theListB = [];
$scope.counter = 0;
$scope.priceOfProducts = 0;
$scope.buyIt = function(){
if ($scope.selectedProduct.unitsInStore>0){
$scope.selectedProduct.unitsInStore--;
$scope.theListB.push($scope.selectedProduct);
$scope.priceOfProducts += $scope.selectedProduct.pricePerUnit;
}else{
alert("The product ID:" + $scope.selectedProduct.productId +"\n" +
"With the name:" + $scope.selectedProduct.productName + "\n"
+"Is out of stock!");
}
$scope.showList();
}
$scope.showList=function(){
$scope.finalList = [];
angular.forEach($scope.theListB, function(productFromListB, key){
var go = true;
angular.forEach($scope.allSProducts, function(productFromStores, key){
if(productFromListB.productId == productFromStores.productId){
// if(go){
$scope.object.product = productFromListB;
$scope.object.unitsOutStore = productFromStores.unitsInStore - productFromListB.unitsInStore;
$scope.object.maxNumber = productFromStores.unitsInStore;
$scope.finalList.push($scope.object);
go = false;
// }
}
});
});
}
so in the end, i got the function $scope.showList()
there i have theListB filed with my 10 or more objects
that data i modify and add to finalList with this line:
$scope.finalList.push($scope.object);
but on the jsp page, it only shows the last added object in the table row
in ng-repeat...
any sugestions?
Here a pic
enter image description here

Create non repeated pairs between results and manufactures, why results are not displayed in `#ModelBranchManufacturer`?

I've this HTML code:
<fieldset class="rpni-border">
<legend class="rpni-border">Model</legend>
<table id="contenedorModelos" style="" class="table table-condensed">
<tbody id="modeloBody">
<tr>
<td>
<input type="radio" value="1" id="selModelo1" name="selModelos">
</td>
<td>Harum.</td>
</tr>
<tr>
<td>
<input type="radio" value="4" id="selModelo4" name="selModelos">
</td>
<td>Pariatur ut.</td>
</tr>
<tr>
<td>
<input type="radio" value="6" id="selModelo6" name="selModelos">
</td>
<td>Tempore animi.</td>
</tr>
<tr>
<td>
<input type="radio" value="8" id="selModelo8" name="selModelos">
</td>
<td>Voluptatem.</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset class="rpni-border">
<legend class="rpni-border">Branch</legend>
<table id="contenedorMarcas" style="" class="table table-condensed">
<tbody id="marcaBody">
<tr>
<td>
<input type="radio" value="3" id="selMarca3" name="selMarcas">
</td>
<td>Ea in sequi.</td>
</tr>
<tr>
<td>
<input type="radio" value="7" id="selMarca7" name="selMarcas">
</td>
<td>Exercitationem.</td>
</tr>
<tr>
<td>
<input type="radio" value="11" id="selMarca11" name="selMarcas">
</td>
<td>Sit alias sit.</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset class="rpni-border">
<legend class="rpni-border">Manufacturer</legend>
<table id="contenedorFabricante" style="" class="table table-condensed">
<tbody id="fabricanteBody">
<tr>
<td>
<input type="checkbox" value="3">
</td>
<td>Ea in sequi.</td>
</tr>
<tr>
<td>
<input type="checkbox" value="7">
</td>
<td>Exercitationem.</td>
</tr>
<tr>
<td>
<input type="checkbox" value="11">
</td>
<td>Sit alias sit.</td>
</tr>
</tbody>
</table>
</fieldset>
<button id="create" type="button">Create</button>
<div id="ModelBranch"></div>
<button id="createM" type="button">Join Model-Branch with Manufacturer</button>
<div id="ModelBranchManufacturer"></div>
And then there is this jQuery:
$(document).ready(function () {
function modelBranchManufacturerObject(config) {
var instance = this;
// initialize class vars
instance.modelKey = config.modelKey;
instance.branchKey = config.branchKey;
instance.manufacturerKeyCollection = [];
instance.globalKey;
// globalKey = modelKey + branchKey
instance.getGlobalKey = function () {
if (!instance.globalKey) {
instance.globalKey = instance.modelKey + '-' + instance.branchKey;
}
return instance.globalKey;
}
instance.addManufacturerKeyCollection = function (manufacturerArray) {
instance.manufacturerKeyCollection = manufacturerArray;
}
}
var modelBranchManufacturerCollection = {};
function addNewRelationModelBranch(modelKey, branchKey) {
var tempModelBranchManufacturerObjectInstance = new modelBranchManufacturerObject({
modelKey: modelKey,
branchKey: branchKey
});
var globalKey = tempModelBranchManufacturerObjectInstance.getGlobalKey();
if (!modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey] = tempModelBranchManufacturerObjectInstance;
} else {
return false;
}
return tempModelBranchManufacturerObjectInstance;
}
function addNewRelationModelBranchManufacturer(globalKey, manufacturerArray) {
if (modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey].manufacturerKeyCollection = manufacturerArray;
} else {
return false;
}
return modelBranchManufacturerCollection;
}
var html = '<table><tbody id="branchModel"></tbody></table>';
$("#ModelBranch").html(html);
$("#create").on("click", function () {
var currModel = $("#modeloBody").find("input[type='radio']:checked").val(),
currBranch = $("#marcaBody").find("input[type='radio']:checked").val(),
ModelBranchObject, tr;
if (currModel && currBranch) {
ModelBranchObject = addNewRelationModelBranch(currModel, currBranch);
if (ModelBranchObject) {
tr = '<tr><td><input type="checkbox" value="' + ModelBranchObject.globalKey + '" /></td>';
tr += '<td>' + ModelBranchObject.modelKey + '-' + ModelBranchObject.branchKey + '</td></tr>';
$("#branchModel").append(tr);
}
}
});
var htmlManufacturer = '<table><tbody id="branchModelManufacturer"></tbody></table>';
$("#ModelBranchManufacturer").html(htmlManufacturer);
$("#createM").on("click", function () {
var checkedModelBranch = $("#branchModelManufacturer").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#fabricanteBody").find("input[type='checkbox']:checked"),
manufacturerColl = [],
trManufacturer,
ModelBranchManufacturerObject;
for (var j = 0; j < checkedManufacturers.length; j++) {
manufacturerColl.push(checkedManufacturers[j].value);
}
console.log(manufacturerColl);
for (var i = 0; i < checkedModelBranch.length; i++) {
ModelBranchManufacturerObject = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
console.log(ModelBranchManufacturerObject);
if (ModelBranchManufacturerObject) {
trManufacturer = '<tr><td><input type="checkbox" value="' + ModelBranchManufacturerObject.globalKey + '" /></td>';
trManufacturer += '<td>' + ModelBranchObject.modelKey + '-' + ModelBranchObject.branchKey;
for (var k = 0; k < ModelBranchObject.manufacturerKeyCollection.length; k++) {
trManufacturer += ModelBranchObject.manufacturerKeyCollection[k] + '<br/>';
}
trManufacturer += '</td></tr>';
$("#branchModelManufacturer").append(trManufacturer);
}
console.log(trManufacturer);
}
});
});
What this code does is allow to pick a model and a branch and create a non repeated pairs between them and also show the results on #modelBranch div. Also allow, I think if I'm not doing something wrong, to pick one|many choices from the results in the previous step (those on #modelBranch) and one|many Manufacturers and again create a non repeated pairs between them but in this case I can not show the results on #ModelBranchManufacturer as I should do so something is not working on my code and I was not able to find where I'm failing so certainly I need some help or advice from you. For clear a bit how the process is take a look at the following example:
Pick Model1/Branch1 and click on "Create Model/Branck Pair", this will generate a pair Model1-Branch1 as image below shows.
Pick Model1/Branch2 and click on "Create Model/Branck Pair", this will generate a pair Model1-Branch2 as image below shows.
Pick Model1/Branch1 and click on "Create Model/Branck Pair", nothing will happen since this pair was added on the (1) step and this is the right behavior to follow meaning do not allow repeated pairs
Now taking the example above you should have a table like this:
checkbox Model1-Branch1
checkbox Model1-Branch2
Following with the logic now:
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and click on "Create Model/Branck-Manufacturer Pair", this should generate something like this below:
Mark to Delete | Model/Branch | Manufacturer
----------------------------------------------------
checkbox | Model1-Branch1 | Manufacturer1
checkbox | Model1-Branch2 | Manufacturer1
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and Manufacturer2 and Manufacturer3 and click on "Create Model/Branck-Manufacturer Pair", this should generate something like this below:
Mark to Delete | Model/Branch | Manufacturer
----------------------------------------------------
checkbox | Model1-Branch1 | Manufacturer1
| | Manufacturer2
| | Manufacturer3
----------------------------------------------------
checkbox | Model1-Branch2 | Manufacturer1
| | Manufacturer2
| | Manufacturer3
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and click on "Create Model/Branck-Manufacturer Pair", nothing should happen since this pair was added on the (1) step and this is the right behavior to follow meaning do not allow repeated pairs
So, why the results from #createM on click event are not show in #ModelBranchManufacturer? Where I'm making something wrong in my code? I made this Fiddle for testing purpose
Ok, after some hours of coffee and a lot of headaches I got the solution and it's working. Maybe this code is a bit different from the main on the post since I made some changes but the idea still:
function modelBranchManufacturerObject(config) {
var instance = this;
// initialize class vars
instance.modelKey = config.modelKey;
instance.branchKey = config.branchKey;
instance.manufacturerCollection = [];
instance.modelName = config.modelName || 'Sin nombre asignado';
instance.branchName = config.branchName || 'Sin nombre asignado';
instance.globalKey;
// globalKey = modelKey + branchKey
instance.getGlobalKey = function () {
if (!instance.globalKey) {
instance.globalKey = instance.modelKey + '-' + instance.branchKey;
}
return instance.globalKey;
}
}
var modelBranchManufacturerCollection = {};
function addNewRelationModelBranch(modelKey, branchKey, modelName, branchName) {
var tempModelBranchManufacturerObjectInstance = new modelBranchManufacturerObject({
modelKey: modelKey,
branchKey: branchKey,
modelName: modelName,
branchName: branchName
});
var globalKey = tempModelBranchManufacturerObjectInstance.getGlobalKey();
if (!modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey] = tempModelBranchManufacturerObjectInstance;
} else {
return false;
}
return tempModelBranchManufacturerObjectInstance;
}
function addNewRelationModelBranchManufacturer(globalKey, manufacturerArray) {
var manufacturerCollection = modelBranchManufacturerObject.manufacturerCollection;
if (modelBranchManufacturerCollection[globalKey]) {
if (manufacturerCollection !== manufacturerArray) {
modelBranchManufacturerCollection[globalKey].manufacturerKeyCollection = manufacturerArray;
return modelBranchManufacturerCollection[globalKey];
}
} else {
return false;
}
}
$("#btnCrearParMarcaModelo").on("click", function () {
var currModel = $("#modeloBody").find("input[type='radio']:checked").val(),
currBranch = $("#marcaBody").find("input[type='radio']:checked").val(),
currModelName = $("#modeloBody").find("input[type='radio']:checked").parent().next('td').text(),
currBranchName = $("#marcaBody").find("input[type='radio']:checked").parent().next('td').text(),
ModelBranchObject, tr;
if (currModel && currBranch) {
ModelBranchObject = addNewRelationModelBranch(currModel, currBranch, currModelName, currBranchName);
if (ModelBranchObject) {
tr = '<tr><td><input type="checkbox" value="' + ModelBranchObject.globalKey + '" /></td>';
tr += '<td>' + ModelBranchObject.modelName + '-' + ModelBranchObject.branchName + '</td><td id="' + ModelBranchObject.globalKey + '"></td></tr>';
$("#parMarcaModeloFabricanteBody").append(tr);
}
}
$("#parMarcaModeloFabricante").show();
});
$("#btnAgregarSelFabricante").on("click", function () {
console.log("d");
var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
manufacturerColl = [],
modelBranchManufacturerCollection;
var j = checkedManufacturers.length, item;
while (j--) {
item = checkedManufacturers[j];
if (item.type && item.type == 'checkbox' && item.checked) {
manufacturerColl.push({
id: item.value,
name: item.parentNode.nextSibling.innerHTML
});
}
}
for (var i = 0; i < checkedModelBranch.length; i++) {
modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
if (modelBranchManufacturerCollection) {
//$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).siblings().attr("rowspan", modelBranchManufacturerCollection.manufacturerKeyCollection.length);
for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).append((modelBranchManufacturerCollection.manufacturerKeyCollection)[k].name + '<br/>');
}
}
}
});

Javascript Search Exact Results Not Part Of

I am trying to use the Javascript search from the below website however was wondering if there is a way to return only the exact term searched for, as if I type part of a word it returns the table row also.
ie. Seach for "Heath" returns the same result as searching Heathesh", is there a simple workaround?
Script: http://heathesh.com/post/2010/05/06/Filtering-or-searching-an-HTML-table-using-JavaScript.aspx
Example: http://heathesh.com/code/javascript/tablesearch/
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Surname</th>
<th>Website</th>
</tr>
<tbody id="data">
<tr>
<td>1</td>
<td>Heathesh</td>
<td>Bhandari</td>
<td>http://heathesh.com</td>
</tr>
<tr>
<td>2</td>
<td>Candice</td>
<td>David</td>
<td>http://candicedavid.com</td>
</tr>
</tbody>
</table>
//define the table search object, which can implement both functions and properties
window.tableSearch = {};
//initialize the search, setup the current object
tableSearch.init = function() {
//define the properties I want on the tableSearch object
this.Rows = document.getElementById('data').getElementsByTagName('TR');
this.RowsLength = tableSearch.Rows.length;
this.RowsText = [];
//loop through the table and add the data to the table search object
for (var i = 0; i < tableSearch.RowsLength; i++) {
this.RowsText[i] = (tableSearch.Rows[i].innerText) ? tableSearch.Rows[i].innerText.toUpperCase() : tableSearch.Rows[i].textContent.toUpperCase();
}
}
Next create the actual JavaScript function to run the search like so:
//onlys shows the relevant rows as determined by the search string
tableSearch.runSearch = function() {
//get the search term
this.Term = document.getElementById('textBoxSearch').value.toUpperCase();
//loop through the rows and hide rows that do not match the search query
for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
}
}
//handles the enter key being pressed
tableSearch.search = function(e) {
//checks if the user pressed the enter key, and if they did then run the search
var keycode;
if (window.event) { keycode = window.event.keyCode; }
else if (e) { keycode = e.which; }
else { return false; }
if (keycode == 13) {
tableSearch.runSearch();
}
else { return false; }
}
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
<input type="text" size="30" maxlength="1000" value="" id="textBoxSearch" onkeyup="tableSearch.search(event);" />
<input type="button" value="Search" onclick="tableSearch.runSearch();" />
</td>
</tr>
</tbody>
</table>
You are matching this with rowText.indexOf() in the code below, that will return the row if the term is found anywhere in the string.
for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
}
To get exact matches, change rowText.indexOf(this.Term) != -1 to rowText.toUpperCase() === this.Term.toUpperCase(). The .toUpperCase() converts both strings to uppercase before comparing to make the search case insensitive.
for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
row.style.display = ((rowText.toUpperCase() === this.Term.toUpperCase()) || this.Term === '') ? '' : 'none';
}
The following code will do a partial search if an exact word match did not give any results:
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Search table</title>
</head>
<body style=" background-color:white;">
<input type="text" size="30"
value=""
id="textBoxSearch"
onkeyup="tableSearch.search(this.value);" />
<div id="table"></div>
<script type="text/javascript">
// create a 4 column table with random text
function getRandomText(len){
ret=[];
for(var i =0;i<len;i++){
ret.push(String.fromCharCode(
Math.floor((Math.random()*(85-65))+65)
));
}
return ret.join("");
}
function createRandomTable(){
var ret=["<table>"],i=0,
j=0;
while(i<50){
j=0
ret.push("<tr>");
while(j<5){
ret.push("<td>");
ret.push(getRandomText(5));
ret.push("</td>");
j++;
}
ret.push("</tr>");
i++;
}
document.getElementById("table")
.innerHTML=ret.join("");
}
createRandomTable();
// Code that does the search
tableSearchF=function(){
//private variables
var table=document.getElementById("table")
.getElementsByTagName("table")[0];
var rows=table.getElementsByTagName("tr");
var rowVals=[];
for(var i=0;i<rows.length;i++){
var tmp=[];
var c=rows[i].getElementsByTagName("td");
for(var j=0;j<c.length;j++){
tmp.push(
(c[j].textContent)?c[j].textContent:c[j].innerText
)
}
rowVals.push(tmp);
}
var searchTable=function(r){
var match=false;
var doPartial=true;
// for each row
for(var i=0;i<rowVals.length;i++){
match=false;
//for each cell
cellmatch:
for(var j=0;j<rowVals[i].length;j++){
if(r.test(rowVals[i][j])===true){
console.log("positive match");
match=true;
doPartial=false;
break cellmatch;
}
}
rows[i].style.display=(match)?"":"none";
}
return doPartial;
}
// publicly available methods
return {
search:function(searchText){
var txt = searchText.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g
,'\\$1')
.replace(/\x08/g, '\\x08'),
r = new RegExp("\\b"+txt+"\\b","igm");
if(searchTable(r)){
// no exact match, do a partial
r=new RegExp(txt,"igm");
searchTable(r);
}
}
}
}
//initialise tableSearch
var tableSearch=tableSearchF();
</script>
</body>
</html>

What is wrong with this Javascript? shopping cart

There is something in this javascript or html which is is allowing the checkboxes to be ticked but for not even half a second. (I need the checks to stay there!) I also need the additems function to work
var computer = new Array();
computer[0] = "10001, Nvidia Geforce GTX 690, 1200";
computer[1] = "10002, Raedon HD 7950, 450";
computer[2] = "20001, Ivy Bridge i7 3770, 400";
computer[3] = "20002, Ivy Bridge i7 3770k, 420";
computer[4] = "20003, Sandy Bridge i7 2700k, 340";
computer[5] = "20004, Bulldozer FX-8150, 270";
computer[6] = "30001, Antec eleven-hundred, 120";
computer[7] = "30002, Coolermaster HAF-X, 170";
computer[8] = "30003, Antec three-hundred, 50";
computer[9] = "30004, Corsair 550D, 160";
computer[10] = "40001, INTEL-ASrock fatal1ty Z77 Professional Motherboard, 250";
computer[11] = "40002, INTEL-ASrock Z77 extreme9 Motherboard, 350";
computer[12] = "40003, AMD-ASrock fatal1ty 990FX Professional Motherboard, 240";
computer[13] = "40004, AMD-ASUS Sabertooth 990FX Motherboard, 260";
Check all checkboxes function
function check() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 1;
} else {
inputs[x].checked = true;
}
}
}
Uncheck all checkboxes function
function uncheck() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 0;
} else {
inputs[x].checked = false;
}
}
}
add checked items to cart
function addItems() {
var leftSide = document.getElementById('table_container_left');
var rightSide = document.getElementById('table_container_right');
var inputs = leftSide.getElementByTagName('input');
var totalPrice = 0;
var basketTable = "<h3>My Basket:</h3><table><thead><tr><th>Item</th><th>Quantity</th><th>price</th><th>Sub-total</th></tr></thead><tbody>";
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].checked == true) {
var quantity = ParseFloat(inputs[x+1).value);
var itemName = computer[x/2].split(",")[1];
var itemPrice = parseFloat(computer[x/2].split(",")[2])
var itemTotal = parseFloat(quantity*itemPrice);
totalPrice += itemTotal;
basketTable += "<tr><td>"+itemName+"</td><td>"+quantity+"</td><td>$"+itemPrice+"</td><td>$"+itemTotal+"</td></tr>";
}
}
basketTable +=" <tr><td> colspan='3'><b>Total:</b></td><td><b>$"+totalPrice+"</b></td></tr></tbody><table>";
rightsSide.innerHTML = basketTable;
}
update quantity to 1 when item is checked
function updateQty(id) {
var targetRow = document.getElementById(id);
var qtyBox = targetRow.getElementsByTagName('input')[1];
if (qtyBox.value == 0) {
qtyBox.value = 1;
} else {
qtyBox.value = 0;
}
}
Here's the HTML as requested
<form name="myForm" action="index.html" method="post">
<div id="table_container_left">
<button onclick="check();">Select All</button>
<button onclick="uncheck();">Unselect All</button>
<button onclick="addItems();">Add Items</button>
<table>
<thead>
<th><u>Item Code</u></th>
<th><u>Item</u></th>
<th><u>Qty</u></th>
<th><u>Price</u></th>
</thead>
<tbody>
<script type="text/javascript">
for(x=0; x<=computer.length-1; x++) {
document.write("<tr id='"+x+"'><td><label><input type='checkbox' name='item' value='"+x+"' onclick='updateQty('"+x+"');'/> "+computer[x].split(",")[0]+"</label></td><td>"+computer[x].split (",")[1]+"</td><td> <input name='qty' id='qty' type='textbox' value='0' onchange='qtychange ('"+x+"');'/></td><td>$"+computer[x].split(",")[2]+"</td></tr>");
}
</script>
</tbody>
</table>
</div>
<div id="table_container_right">
<table id="shoppingBasket">
<input name='selectAll' type='button' value='Select All' onclick="itemSelected();"/>
<input name='clearAll' type='button' value='Clear All' onclick=""/>
<input name='removeItem(s)' type='button' value='Remove Item(s)' />
<input name='sortItemCode' type='button' value='Sort by Item Code' disabled='disabled' />
<input name='sortPrice' type='button' value='Sort by Price' disabled='disabled' />
</tbody>
</table>
</div>
</div>
</form>
Your JS syntax is way off, this is what it should look like
function addItems(field) {
for (i = 0; i <= field.length-1; i++)
{
if (field[i].checked == true)
{
if (computer[i]!=null) {
selected[i] = computer[i];
}
}
}
}
Half of your if statements are missing parentheses, that's some basic wrongfulness.
I don't know what and where should any of the variables be, but here is my best shot:
function addItems(field) {
var i;
for (i = 0; i < field.length; i++) {
if (field[i].checked === true) {
if (computer[i] !== null) {
selected[i] = computer[i];
}
}
}
}
You are using i = 0 rather than var i = 0, which will introduce a global variable. This could be a problem if you're writing similar code elsewhere.
Your if-statements are not statements at all. They look like pseudo-code. You're also comparing with = rather than ==, which will cause an assignment rather than a condition, even if you fix up your syntax.
You are not properly indenting your code, which will make you much more prone to introduce new errors.
These are the general issues I notice immediately. Of course, heaps of things could be wrong with this code. fields might not be an array, computer and selected might not match the size of fields, etc.
If you have any specific problem, please describe that, and we may be able to address it.

Categories