-4

I'm starting to learn JQuery.

Right now I want to take the value from my paragraph and give it +1 everytime I click on it. This is what I've tried:

<body>
    <p>0</p>
    <script>
        $("p").click(function(){
            // code...
        });
    </script>
</body>

This is my script

Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
user3406286
  • 59
  • 1
  • 2
  • 8

4 Answers4

2

Try this:

  $( "p" ).click(function(){
     $(this).html(parseInt($(this).html(),10)+1);
  });

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
2

You can do this as simple as this:

$(function(){ // you can wrap it here with in document ready block
   var i = 0;
   $("p").click(function(){
       $(this).html(i++);
   });
});

or may be a better one:

$(function(){ // you can wrap it here with in document ready block
   $("p").click(function(){
       $(this).html(+this.textContent + 1);
   });
});

Fiddle

Jai
  • 74,255
  • 12
  • 74
  • 103
1
var count=0;
$( "p" ).click(function(){
    count++;    
    $(this).text(count);
});
Brocco
  • 62,737
  • 12
  • 70
  • 76
Balachandran
  • 9,567
  • 1
  • 16
  • 26
0
this.firstChild.nodeValue = +this.firstChild.nodeValue + 1;

MOSR EFFICIENTS! :p

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592