Grayish
Grayish

Reputation: 187

Javascript & HTML - count number of times button is clicked

So I have a 'add' button that is beside every item in an inventory and I'm trying to figure out how I could manipulate that button so that it works as a counter. My issue is these buttons were declared in a javascript file, so there's no button id from the HTML file that I can use for my buttonClicked() function which is basically supposed to count the number of times any 'add' button was clicked in total.

So for example my page looks like this right now:

Laptops

iMac $2000 [ADD BUTTON]

Dell $600 [ADD BUTTON]

Computers

Windows PC $1300 [ADD BUTTON]

If I were to click the button beside the iMac and the button beside the Windows PC, then the buttonClicked() function should print "You clicked the button 2 times." I'm just having trouble trying to access the button variables that were defined in the javascript file in the line 'newContent += <input type=button value="Add" onclick="add(this)"/>'and not the HTML file. That button defined in the HTML file is a select button that is different from the one I'm trying to access. Any help would be appreciated.

let count;

function init() {
  count = 0;
  let button = document.getElementById("but");
  button.onclick = buttonClicked;
}


function buttonClicked() {
  count++;
  let div = document.getElementById("list");
  div.innerHTML = "You clicked the button " + count + " times.";
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach(key => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += '<div>';
        newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
        newContent += `<input type=button value="Add" onclick="add(this)"/>`
        newContent += '</div>';
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(add) {
  console.clear();
  console.log(add.closest('div').textContent.trim())
}


let electronics = {
	store: "Mike's Computers",
	inventory: {
		"Laptops": {
			0: {
				brand: "iMac",
				cost: 2000
			},
			1: { 
				brand: "Dell",
				cost: 600
			}
		},
		"Computers": {
			2: {
				brand: "Windows PC",
				cost: 1300
			}
		}
	}
};
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); buttonClicked(this)">
      <option value="none">Select a store</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" onclick="showOptions(); buttonClicked()" />
  </form>

</div>
<div id="div"></div>

Upvotes: 1

Views: 2515

Answers (3)

vineeta kande
vineeta kande

Reputation: 44

You have not selected proper buttion id. If you want to update the button value after each adjacent button clicked then here is the code.

function buttonClicked(id, c) {
  c++;
  document.getElementById(id).value = c;
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach((key) => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += '<div>';
        newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
        newContent += `<input type=button id=${item.id} value="Add" onclick="add(this)"/>`
        newContent += '</div>';
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(e) {
  let id = e.attributes[1].value;
  let val = e.attributes[2].value;
  if(val == 'Add'){
    buttonClicked(id, 0)
  } else {
    buttonClicked(id, val);
  }
}


let electronics = {
    store: "Mike's Computers",
    inventory: {
        "Laptops": {
            0: {
        id: 1,
                brand: "iMac",
                cost: 2000
            },
            1: { 
        id: 2,
                brand: "Dell",
                cost: 600
            }
        },
        "Computers": {
            2: {
        id:3,
                brand: "Windows PC",
                cost: 1300
            }
        }
    }
};
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <div><h1>Welcome</h1></div><br />
<div class="dropdown">
    <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); buttonClicked(this)">
        <option value="none">Select a restaurant</option>
        <option value="Electronics">Electronics</option> 
    </select>
    <input type=button id = "but" value="Select" onclick="showOptions(); buttonClicked()" />
    </form>

</div>

Upvotes: 1

mplungjan
mplungjan

Reputation: 178350

Like this?

  • initialise count to 0
  • add event listener to the select - remove the click from the select
  • add eventlistener to future buttons using delegation
  • Use a separate div for the message

let count=0;

let electronics = {	store: "Mike's Computers",	inventory: {		"Laptops": {			0: {				brand: "iMac",				cost: 2000			},			1: { 				brand: "Dell",				cost: 600			}		},		"Computers": {			2: {				brand: "Windows PC",				cost: 1300			}		}	}};


window.addEventListener("load", function() {
  count = 0;
  document.getElementById("list").addEventListener("change", function() {
    showOptions(this);
  })
  
  document.getElementById("div").addEventListener("click", function(e) {
    const tgt = e.target;
    if (tgt.type==="button") {
      add(tgt)
    }
  })
})


function buttonClicked() {
  count++;
  let div = document.getElementById("msg");
  div.innerHTML = "You clicked the button " + count + " time"+(count===1?"":"s")+".";
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  div.innerHTML = "";
  if (userPicked === 'none') return;
  var newContent = (electronics.store);
  newContent += '<div>';
  Object.keys(electronics.inventory).forEach(key => {
    newContent += key;
    newContent += '<div>';
    var items = Object.values(electronics.inventory[key]);
    items.forEach(item => {
      newContent += '<div>';
      newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
      newContent += `<input type=button value="Add""/>`
      newContent += '</div>';
    });
    newContent += '</div>';
  });
  newContent += '</div>';
  div.innerHTML = newContent;

}

function add(add) {
  buttonClicked()
  console.clear();
  console.log(add.closest('div').textContent.trim())
}
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target">
      <option value="none">Select a store</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" />
  </form>

</div>
<div id="div"></div>
<div id="msg"></div>

Upvotes: 2

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

you don't put initial value for count let count = 0;

and have to call buttonClicked() on every Add button click

let count = 0;

function init() {
  count = 0;
  let button = document.getElementById("but");
  button.onclick = buttonClicked;
}


function buttonClicked() {
  count++;
  let div = document.getElementById("coutner");
  div.innerHTML = "You clicked the button " + count + " times.";
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach(key => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += '<div>';
        newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
        newContent += `<input type=button value="Add" onclick="add(this)"/>`
        newContent += '</div>';
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(add) {
  console.clear();
  console.log(add.closest('div').textContent.trim());
  buttonClicked();
}


let electronics = {
  store: "Mike's Computers",
  inventory: {
    "Laptops": {
      0: {
        brand: "iMac",
        cost: 2000
      },
      1: {
        brand: "Dell",
        cost: 600
      }
    },
    "Computers": {
      2: {
        brand: "Windows PC",
        cost: 1300
      }
    }
  }
};
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); buttonClicked(this)">
      <option value="none">Select a restaurant</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" onclick="showOptions(); buttonClicked()" />
    <div><mark id="coutner"></mark></div>
  </form>

</div>
<div id="div"></div>

Upvotes: 1

Related Questions