nn2 nn2 - 4 months ago 32
jQuery Question

JavaScript counter

Everytime a specific action is made in JavaScript for example this:

<script type="text/javascript">
$(function() {
$('#typing').keyup(function () {
switch($(this).val()) {
case 'containment':
// HERE
break;
}
});
});
</script>


inside the //HERE would be where the 'counter' was made. Then add 1 everytime the case 'containment' is run if it's not already run. So if I run containment case once.. it adds. If I run it again.. it will not -- see what I am talking about?

Answer

You have to define the counter before the counting starts. Then you can add to it later, like this:

<script type="text/javascript">
var count = 0;  //(or any number you need)
$(function() {
    $('#typing').keyup(function () {
     switch($(this).val()) {
       case 'containment':
          count++;
break;
     }
    });
});
</script>