Generate number counting when clicking

1

Is there any way that when I click on an element, update the number of tag to a higher value?

Ex: The value of the tag default is 1 , the tag n , n="1" when clicking on the element updates to n="2" and so on.

    
asked by anonymous 03.01.2018 / 23:30

3 answers

1

If your goal is to just bookmark your browser, here is an example. But as you indicated the PHP tag in the question ... if you want to persist this count on the server, you need to prepare a structure to store that information.

$('document').ready(function(){
  
  $('.tag').on('click', function(){
      var contador = $(this).attr('n');
      var total = ++contador;
      $(this).find('span:first').text(total);
      $(this).attr('n', total);
     
  });
});
div{
  background-color: #ccc;
  display:block;
  position:relative;
  min-width: 30px;
  float:left;
  padding: 5px 5px 5px 5px;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="tag" n="0"> tag (<span class="count">0</span>)</div>
<div class="tag" n="0"> outra tag (<span class="count">0</span>)</div>
    
03.01.2018 / 23:50
2

You can use setAttribute and incrementing the value at each click with addEventListener .

I've placed a counter on the buttons to illustrate, but if you view the " preview element " of the browser, you will see that the n attribute is also being changed.

var els = document.querySelectorAll("#tags button");
for(x=0; x < els.length; x++){
   els[x].addEventListener("click", function(){
      var soma = parseInt(this.getAttribute("n"))+1;
      this.setAttribute("n",soma);
      this.innerText = soma;
   });
}
<div id="tags">
<button type="button" n="1">1</button>
<button type="button" n="1">1</button>
</div>
    
04.01.2018 / 00:08
1

You can use a button that when clicking increases the value of the input or any other tag. Here is an example:

  var botao = document.getElementById('botao');
  botao.addEventListener("click", function() {
    var input = document.getElementById("input");
    var valor_atual = input.value;
    valor_atual++;
    input.value = valor_atual;
  });
    
03.01.2018 / 23:41