Unable to take value from collection (using GetElementsByClassName) - javascript

I'm trying to show an output that gets its value from a collection.
Here is the code.
For 'schnapps' which shows twice, I manage to get the output I want.
But for 'potato' I am unable to show output.
<tr>
<td>Schnapps Distillery</td>
<td class='inputText schnapps'></td>
<td>600 Farmers & Workers</td>
</tr>
<tr>
<td colspan="3">
<div class='inline'>
<div class='inline potato'></div><img class='smallLogos'
src='../images/potato.png' /> -->
<div class='inline schnapps'></div><img class='smallLogos'
src='../images/schnapps.png' />
</div>
</td>
</tr>
schnappsElement = document.getElementsByClassName("schnapps");
potatoElement = document.getElementsByClassName("potato");
//schnapps
for (i = 0; schnappsElement[i] != null; i++) {
schnappsElement[i].innerHTML = Math.ceil((Number(farmInput.value) + Number(workInput.value)) / 600);
}
potatoElement.innerHTML = schnappsElement[0].value;
Both commands in JS are activated by a listener command I didn't include.
The command works because I get the right output for Schnapps.
What I want is for potatoElement to have (and show) the same value as schnappsElement.

The schnappsElement[0] doesnt not have .value(). Use .innerHTML instead.
And also, potatoElement is an array - you need to use it as potatoElement[0].
schnappsElement = document.getElementsByClassName("schnapps");
potatoElement = document.getElementsByClassName("potato");
//schnapps
for (i = 0; schnappsElement[i] != null; i++) {
schnappsElement[i].innerHTML = Math.ceil((Number(farmInput.value) + Number(workInput.value)) / 600);
}
potatoElement[0].innerHTML = schnappsElement[0].innerHTML;
Or you could simply include them both in the Loop:
schnappsElement = document.getElementsByClassName("schnapps");
potatoElement = document.getElementsByClassName("potato");
//schnapps
for (i = 0; schnappsElement[i] != null; i++) {
var value = Math.ceil((Number(farmInput.value) + Number(workInput.value)) / 600);
schnappsElement[i].innerHTML = value;
if (potatoElement[i]) { potatoElement[i].innerHTML = value }
};

Related

How to remove data local storage in specific index or row

in my code, if I run, my data in local storage remove all. how I can delete 1 row where I choice
I confuse how to delete row in table data from local storage
my problem now is, when i click button delete in row table, row choice removed but data in local storage not remove and then when i refresh page, data show again.
function hapus(r){
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
localStorage.removeItem('dataProduk');
}
Full Code like this
<script type="text/javascript">
$(document).ready(function() {
$('.js-example-basic-single').select2();
$('#getProduks').change(function(e){
let data = $('#getProduks').val();
let datas = data.split('|');
let idProduk = datas[0];
let hargaProduk = datas[1];
let stokProduk = datas[2];
let namaProduk = datas[3];
$('#hargaProduk').val('');
$('#hargaProduk').val(hargaProduk);
})
let dataStore = localStorage.getItem('dataProduk') ? JSON.parse(localStorage.getItem('dataProduk')) : [];
let subAllTotal = 0;
for (var i = 0; i < dataStore.length; i++){
let table = `
<tr>
<td width="10" align="center" scope="row"></td>
<td><button type="submit" onclick="hapus(this)"><i class="fa fa-trash-o"></i></button></td>
<td> ${dataStore[i].namaProduk}</td>
<td> ${dataStore[i].hargaProduk}</td>
<td> ${dataStore[i].disProduk}</td>
<td> ${dataStore[i].jumProduk}</td>
<td> ${(dataStore[i].hargaProduk * dataStore[i].jumProduk) - (dataStore[i].hargaProduk * dataStore[i].jumProduk * dataStore[i].disProduk/100)}</td>
</tr>
`
$('tbody').append(table);
subAllTotal += (dataStore[i].hargaProduk * dataStore[i].jumProduk) - (dataStore[i].hargaProduk * dataStore[i].jumProduk * dataStore[i].disProduk/100)
}
$('#subAllTotal').html(jadiinRupiah(subAllTotal));
$('#tambahProduk').click(function(){
let namaP = $('#getProduks').val().split('|')[3];
let hargaP = $('#hargaProduk').val();
let disP = $('#getDis').val();
let jumP = $('#getJum').val();
let data = {
namaProduk: namaP,
hargaProduk: hargaP,
disProduk: disP,
jumProduk: jumP
}
dataStore.push(data)
localStorage.setItem('dataProduk',JSON.stringify(dataStore))
let subAllTotal = 0;
let table = `
<tr>
<td width="10" align="center" scope="row"></td>
<td><button type="submit" onclick="hapus(this)"><i class="fa fa-trash-o"></i></button></td>
<td> ${data.namaProduk}</td>
<td> ${data.hargaProduk}</td>
<td> ${data.disProduk}</td>
<td> ${data.jumProduk}</td>
<td> ${(data.hargaProduk * data.jumProduk) - (data.hargaProduk * data.jumProduk * data.disProduk/100)}</td>
</tr>
`
$('tbody').append(table);
for (var i = 0; i < dataStore.length; i++){
//subAllTotal += (data.hargaProduk * data.jumProduk) - (data.hargaProduk * data.jumProduk * data.disProduk/100)
subAllTotal += (dataStore[i].hargaProduk * dataStore[i].jumProduk) - (dataStore[i].hargaProduk * dataStore[i].jumProduk * dataStore[i].disProduk/100)
}
$('#subAllTotal').html(jadiinRupiah(subAllTotal));
})
});
$('#hapusProduk').click(function(){
localStorage.clear();
});
function hapus(r){
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
localStorage.removeItem('dataProduk');
}
function jadiinRupiah(total) {
return new Intl.NumberFormat('en-US', {style: 'currency', currency: 'IDR'}).format(total).split('IDR')[1].trim()
}
You need to get the current array, remove the row and save it again.
function hapus(r){
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
let data = localStorage.getItem('dataProduk');
data.splice(i,1); //remove data[i]
localStorage.setItem('dataProduk', data);
}
I'm not sure what dataProduk looks like - if it's an array the above solution will work but if it's an object you'll have to use dataProduk.filter

Why does my value keep returning as "NaN"?

Here is the link to the jsbin.
I was almost finished with my project (I thought I was) and then I tested it out. It is supposed to add buttons with the chosen title of the task and the number of points it awards. Every time the button is clicked the points would be added on to the "Points" section and every 500 points my "Level" would increase.
Upon finishing it, it worked. Then I went to clear the localStorage since that's what I used to save the information, but I wanted to start over. When I did that, the 'Points' section, or 'results' value, keeps returning as "NaN". The code is exactly the same as it was when it worked. Can someone please tell me how to fix this problem, thank you in advance.
Here is the code. (Used bootstrap for CSS)
HTML
<center>
<br>
<h2> Add task </h2>
<div class='well' style='width:500px' id="addc">
<div id="addc">
<input class='form-control' style='width:450px' id="btnName" type="text" placeholder="New Task" /><br>
<input class='form-control' style='width:450px' id="btnPoints" type="text" placeholder="Points" /><br>
<button id="addBtn">Add</button>
</div> </div>
<div class='well' style='width:230px' id="container">
</div>
<hr style="width:400px;">
<h3>Points </h3>
<div id="result">0</div>
</div>
<hr style="width:400px;">
<div style="width:400px;">
<h3>Level
<p id='lvl'>0</p>
</div>
<hr style="width:400px;">
</center>
JavaScript
var res = document.getElementById('result');
res.innerText = localStorage.getItem('myResult');
var level = document.getElementById('lvl');
level.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for(var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if(!btnName)
btnName = "Button ?";
if(!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-danger';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
var result = document.getElementById('result');
result.innerText = parseInt(result.innerText) + parseInt(pts);
var lvl = 0;
var a = 100;
while (result.innerText > 5*a) {
lvl+=1;
a+=100;
}
document.getElementById('lvl').innerText = lvl;
var res = document.getElementById('result');
localStorage.setItem("myResult", res.innerText);
var level = document.getElementById('lvl');
localStorage.setItem("myLevel", level.textContent);
}
You were parsing result.innerText as a number, but its value, initially, was actually either NaN or nothing, both which end up being NaN. One fix is to just check if it parsed to a number, and if it didn't, fall back to 0.
I just basically changed that and removed some getElementByIds that, in my opinion, were redundant, check the addToResult function:
http://jsfiddle.net/owc26a0p/1/
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fallback to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
while (result > 5 * a) {
lvl += 1;
a += 100;
}
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
I ended up using jsFiddle since I couldn't always get jsBin to save my changes. Good luck.

Javascript shows NaN in wrong form-field in IE - works in Firefox and chrome

I am trying to setup a small article chooser. While it works in Firefox and Chrome, as well as IE7, it has problems on IE8 and IE9.
In IE 8 and 9 it changes to "increase" field to "NaN" when clicked. (edit: solved by placing a letter in front of the number)
In IE9 it updates the "Warenkorb", but places "NaN" or "\/" in
the field for "Anzahl". (edit: solved by placing a letter in front of the number)
In IE8 it completely ignores the update function. (edit: is related to the innerHTML-Bug)
To me it seems that somehow I can not reach the form itself. I have already tried to use document.forms[0] and document.getElementById["bestmult"] instead, in case the delivered object is not the field inside the form, but that did not change anything.
I feel like the solution is very simple, but I just can not put my finger on it.
Here is the code:
<script>
var sumarray = new Array();
var artarray = new Array();
var costarray = new Array();
var counter=0;
function increase(obj, field, type){
var form = obj.form;
var value = parseInt(form.elements[field].value, 10);
value++;
form.elements[field].value = value;
updateCosts(obj, field, type);
}
function decrease(obj, field, type){
var form = obj.form;
var value = parseInt(form.elements[field].value, 10);
if(value > 0){
value--;
form.elements[field].value = value;
updateCosts(obj, field, type);
}
}
function updateCosts(obj, field, type){
var form = obj.form;
var exist = artarray.indexOf(form.elements[field].name);
var preis = 0;
if (type == 'b'){
preis = 19.95;
}else if (type == 'p') {
preis = 29.95;
}
if (exist != -1){
if (form.elements[field].value == 0){
sumarray.splice(exist , 1);
artarray.splice(exist , 1);
costarray.splice(exist , 1);
counter--;
}else {
sumarray[exist] = form.elements[field].value;
artarray[exist] = form.elements[field].name;
costarray[exist] = preis;
}
}else {
sumarray[counter] = form.elements[field].value;
artarray[counter] = form.elements[field].name;
costarray[counter] = preis;
counter++;
}
var completestring = "";
if (counter > 0) {
var product = 0;
completestring += "<h1>Warenkorb</h1><table border=0><tr style='background:gray;' align='center'><td width=110 align='center'>Artikel</td><td width=80>Anzahl</td><td align='center' width=60>Preis</td><td align='center' width='40'>Del</td></tr>";
for(var i=0;i<counter;i++){
completestring += "<tr><td>"+artarray[i].replace("_", " ")+"</td><td align=center>"+sumarray[i]+"</td><td align=center>"+costarray[i]+"</td><td align=center><img src='img/trash.png' onclick='setZero(\""+artarray[i]+"\")'></td></tr>";
product += parseInt(sumarray[i])*parseInt(costarray[i]);
}
completestring += "</table><h2>"+(product).toFixed(2)+"</h2>";
} else {
completestring += "<h1>Warenkorb</h1>";
}
document.getElementById("sum").innerHTML = completestring;
}
function setZero(element) {
var form = document.forms[0];
form.elements[element].value = "0";
var obj = form.elements[element];
updateCosts(obj, element, "b");
}
</script>
<div id="sum">
</div>
<form id="bestmult" action="test2.html" method="post">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td rowspan="2"><input type="text" name="1_Basis" value="0" onblur="updateCosts(this, '1_Basis', 'b')" /></td>
<td><input type="button" value=" /\ " onclick="increase(this, '1_Basis', 'b')" class="button" ></td>
</tr><tr>
<td><input type="button" value=" \/ " onclick="decrease(this, '1_Basis', 'b')" class="button" ></td>
</tr>
</table>
This code is of cause not everything there is (although everything that could potentially influence the problem at hand), so don't bother with the script tags, or the incomplete form, these where just added for completion, to show how it all fits together without having to post the whole code.
edit: it seems that IE8 and 9 have a problem with the way I named by textfields. I could resolve most of the problem by simply putting a z at the start which I can later simply strip to regain to proper text. Now it is just IE8 that does not seem to like innerHTML. I did find a lot on this on the Internet, yet nothing that really works.
Check my modifications in your script code
<script>
var sumarray = new Array();
var artarray = new String();
var costarray = new Array();
var counter=0;
function increase(obj, field, type){
var form1 = obj.form;
//alert(obj.form1.elements[0].value);
var value = parseInt(form1.elements(field).value, 10);
value++;
form1.elements(field).value = value;
updateCosts(obj, field, type);
}
function decrease(obj, field, type){
var form = obj.form;
var value = parseInt(form.elements(field).value, 10);
if(value > 0){
value--;
form.elements(field).value = value;
updateCosts(obj, field, type);
}
}
function updateCosts(obj, field, type){
var form = obj.form;
var exist = artarray.indexOf(form.elements(field).name);
var preis = 0;
if (type == 'b'){
preis = 19.95;
}else if (type == 'p') {
preis = 29.95;
}
if (exist != -1){
if (form.elements(field).value == 0){
sumarray.splice(exist , 1);
artarray.splice(exist , 1);
costarray.splice(exist , 1);
counter--;
}else {
sumarray[exist] = form.elements(field).value;
artarray[exist] = form.elements(field).name;
costarray[exist] = preis;
}
}else {
sumarray[counter] = form.elements(field).value;
artarray[counter] = form.elements(field).name;
costarray[counter] = preis;
counter++;
}
var completestring = "";
if (counter > 0) {
var product = 0;
completestring += "<h1>Warenkorb</h1><table border=0><tr style='background:gray;' align='center'><td width=110 align='center'>Artikel</td><td width=80>Anzahl</td><td align='center' width=60>Preis</td><td align='center' width='40'>Del</td></tr>";
for(var i=0;i<counter;i++){
completestring += "<tr><td>"+artarray[i].replace("_", " ")+"</td><td align=center>"+sumarray[i]+"</td><td align=center>"+costarray[i]+"</td><td align=center><img src='img/trash.png' onclick='setZero(\""+artarray[i]+"\")'></td></tr>";
product += parseInt(sumarray[i])*parseInt(costarray[i]);
}
completestring += "</table><h2>"+(product).toFixed(2)+"</h2>";
} else {
completestring += "<h1>Warenkorb</h1>";
}
document.getElementById("sum").innerHTML = completestring;
}
function setZero(element) {
var form = document.forms[0];
form.elements[element].value = "0";
var obj = form.elements[element];
updateCosts(obj, element, "b");
}
</script>
For ie8 indexOf() method for Array will give error. Check this
I think the problem is related to passing "this" to the function. It seems to be passing the button.
Try replacing
var form = obj.form;
with
var form=document.forms[0]
and ignore the reference to "obj"
Ok, so here is the solution packed together into one answer:
I was facing two problems:
the first one was, that an attribute name in XML can not start with a Number. I solved this by simply adding a letter in front, which i could delete for the String lateron using the replace-function.
The second problem was that the IE8 does not have the Array function indexOf(). Thank you 555k for your help here, you gave me the final piece to the puzzle. I wrote a small workaround, that suits my situation:
var exist = -1;
var needle = form.elements[field].name;
for (var i=0;i<counter;i++){
if (artarray[i].indexOf(needle) != -1){
exist = i;
}
}
This does exactly what I want, so it works for my problem. It is, of cause, not a solution to the problem of a nonexistant "indexOf()" for an aged browser, but maybe someone can use this.

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

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