Web Analytics Made Easy -
StatCounter Buttons with count on every click - CodingForum

Announcement

Collapse
No announcement yet.

Buttons with count on every click

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Buttons with count on every click

    hello, can you help me create a button with counts on every click that applicable in many buttons.


    my codes below only works with one or first button only, its not working with the other buttons

    Code:
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Increment count when button is clicked</title>
      </head>
    
      <body>
    
        <input type="button" value="Add to Cart" id="countButton" /><span id="displayCount">0</span>
       <br> <br>
         <input type="button" value="Add to Cart" id="countButton" /><span id="displayCount">0</span>
    
        <script type="text/javascript">
          var count = 0;
          var button = document.getElementById("countButton");
          var display = document.getElementById("displayCount");
    
          button.onclick = function(){
            count++;
            display.innerHTML = count;
          }
        </script>
      </body>
    </html>
    Last edited by finoy_ako; Oct 3, 2016, 12:08 PM. Reason: editting
    Selling Affordable Website Themes & Services
    https://www.flyingthemes.com

  • #2
    An ID has to be unique for the whole document. Use a class instead and the function getElementsByClassName() and a for loop for adding the event listeners.

    Comment


    • #3
      Something along these lines may steer you on the right track if you can use jquery
      Code:
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <title>Increment count when button is clicked</title>
      </head>
          <body>
              <input type="button" value="0" class="countButton" /><span id="displayCount"></span>
              <br> <br>
              <input type="button" value="0" class="countButton" /><span id="displayCount"></span>
              <script src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>
              <script type="text/javascript">
                  $( ".countButton" ).each(function() {
                      $(this).click(function(){
                          var count =  $(this).val();
                          count++;
                          $(this).prop('value', count);
                      });
                  });
              </script>
          </body>
      </html>

      Comment


      • #4
        Alternative without JQuery
        Code:
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Increment count when button is clicked</title>
        <style type="text/css">
         .countButton { background-color: lime; }
        </style>
        
        </head>
        <body>
         <input type="button" value="0" class="countButton" />
         <br> <br>
         <input type="button" value="0" class="countButton" />
        
        <script>
          function init() {
            var sel = document.getElementsByClassName('countButton');
            for (var i=0; i<sel.length; i++) {
              sel[i].onclick = function() { this.value = this.value*1 + 1; }
            }
          } init();
        </script>
        </body>
        </html>

        Comment


        • #5
          One of my basic rules is that anything you do for something like shopping, or any form in general is provide scripting off fallbacks. Using a button this way cannot provide that... Remember, GOOD JavaScript should enhance the page's functionality, not supplant it... and if you can't make a page that works without JavaScript FIRST, you likely have no business adding scripting to it.

          To that end I would have a submit as the actual "button" element, but use a label as the visible button. You could then use CSS to hide the actual input. This would let the value of the input reflect what the scripting target is for, and be trapped server-side for scripting off. Just check isset($_POST['addToCart']) and if it is set, the value will tell you which item to increment, you then spit it back at the client properly adjusted.

          Remember, clicking on a label is the SAME as clicking on the input/select/textarea it is "for".

          Code:
          <input type="submit" name="addToCart" id="addToCart_0" value="item_0" class="addToCart">
          <label for="addToCart_0">Add To Cart</label>
          <input id="item_0" value="0">
          <br>
          <input type="submit" name="addToCart" id="addToCart_1" value="item_1" class="addToCart">
          <label for="addToCart_1">Add To Cart</label>
          <input id="item_1" value="0">
          The scripting just enhances this preventing the click event from doing the submit, and instead doing our increment locally.

          Code:
          function eventAdd(e, event, callback) {
          	if (e.addEventListener) e.addEventListener(event, callback, false);
          	else e.attachEvent('on' + event, callback);
          }
          
          function eventProcess(e, prevent) {
          	e = e || window.event;
          	if (!e.target) e.target = e.srcElement;
          	if (prevent) {
          		// this MAY be overkill... Oh, who are we kidding, it is!
          		e.cancelBubble = true;
          		if (e.stopPropagation) e.stopPropagation();
          		if (e.preventDefault) e.preventDefault();
          		e.returnValue = false;	}
          	return e;
          }
          
          function addToCart(e) {
          	e = eventProcess(e, true);
          	e.target.data_forElement.value++;
          }
          
          var
          	adders = document.getElementsByClassName('addToCart'),
          	aCount = adders.length;
          	
          for (var i = 0; i < aCount; i++) {
          	adders[i].data_forElement = document.getElementById(adders[i].value);
          	eventAdd(adders[i], 'click', addToCart);
          }
          Couple handy helper functions to make sure our event handlers work in both JavaScript and jScript (if you care about really old IE, you'll need to polyfill getElementsByClassName or walk the DOM to get the proper elements to hook), our addToCart as a proper function instead of an anonymous so we aren't making multiple copies in memory, storing the count so we're not calling .length every loop. I store the element the submit.addToCart is for as a data_forElement attribute on the input so we don't have to get it in realtime -- greatly speeding up our click routine. The direct increment (++) on value also means we don't have to play games with worrying about typecasting.

          A bit more code, but more robust and reliable than anything the bloated wreck of developer ineptitude jQuery would give you... and has all the hooks to properly gracefully degrade so you can also make the page work scripting off. Best of all, it moves the values into input so a normal form submit will transmit how many are in the cart properly without having to dick around with even MORE scripttardery... and since it's a input, the user can also type in how many they want.
          Walk the dark path, sleep with angels, call the past for help.
          https://cutcodedown.com
          https://medium.com/@deathshadow

          Comment

          Working...
          X