Home > Software engineering >  Count each value on button
Count each value on button

Time:06-16

I try to count each value in each button

This is the example

The PHP Code

<?php for($i = 0; $i < 5; $i  ){?>
<a  data-id="<?php echo($i)?>" id="click[<?php echo($i)?>]"> 
Click Me <h7 id="count[<?php echo($i)?>]">(0)</h7>
</a>
<?php }?>

Jquery

$(document).ready(function() {
  var i = 0;
  $(".btn-count").click(function(){
     i  ;
     var id = $(this).data('id');
     $("#count[" id "]").text(i);
  });
}

But it didn't work at all. Anyone can tell me where this code goes wrong?

CodePudding user response:

You don't need to use the id's for this, you can use .find() to find the child based on your html.

Then get the "count" value from your element and add 1 to it.

$(document).ready(function() {
  $(".btn-count").click(function() {
    $(this).find("h6").text(function(i, n) {
      var count =  n.match(/\(([^)] )\)/)[1];
      return `(${count 1})`
    });
  });
})

Demo

$(document).ready(function() {
  $(".btn-count").click(function() {
    $(this).find("h6").text(function(i, n) {
      var count =  n.match(/\(([^)] )\)/)[1];
      return `(${count 1})`
    });
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a  data-id="<?php echo($i)?>" id="click[<?php echo($i)?>]"> 
Click Me <h6 id="count[<?php echo($i)?>]">(0)</h6>
</a>


<a  data-id="<?php echo($i)?>" id="click[<?php echo($i)?>]"> 
Click Me <h6 id="count[<?php echo($i)?>]">(0)</h6>
</a>

Problem with having a global counter as you have in var i = 0; it will no represent the button you have click, but all of them.

CodePudding user response:

your code can be simply modified to this

<button  data-id="1" id="click1"> 
Click Me <h7 id="count1">(0)</h7>
</button>

<button  data-id="2" id="click2"> 
Click Me <h7 id="count2">(0)</h7>
</button>
$(document).ready(function() {

  $(".btn-count").click(function(){ 
     var id = $(this).data('id');
    var value = $(this).data('value');
    value  
    $(this).data('value', value);
    console.log(id)
    console.log( $("#count" id))
     $("#count" id).text(value);
  });
})

Here is also a demo for the code

https://codepen.io/BubuKiki/pen/YzegWMg

The problem is with the special characters, it does not seem to find them. Hope this helps.

  • Related