Rabcor
Rabcor

Reputation: 249

How to create and use integer in jquery?

I'm using jquery in a html project. I'm trying to make an integer that will change each time a button is pressed to count how many times it has been pressed and change the result.

Here's pretty much the code i've written

<script>
$(document).ready(function(){
int x = 0;
$("#buttonid").click(function(){
    if(x == 0)
    {
       $("#text").fadeIn();
       $("#othertext").fadeOut();
    }
});
});
</script>

What am i doing wrong? i couldn't understand the documentation properly

Upvotes: 0

Views: 166

Answers (3)

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

JavaScript support dynamic types.
This means that the same variable can be used as different types

use var to define datatype.

var x;               // Now x is undefined
var x = 5;           // Now x is a integer
var x = 5.20;        // Now x is a double or float
var x = "John";      // Now x is a String

<script>
 $(document).ready(function(){
 var x = 0;// x is integer here
 $("#buttonid").click(function(){
if(x == 0);
{
   $("#text").fadeIn();
   $("#othertext").fadeOut();
}
});
});
 </script>

Upvotes: 0

Christian Ternus
Christian Ternus

Reputation: 8492

Well, firstly, Javascript has no int keyword. You want var x = 0;.

Next, you'll want to actually do the incrementing. You have a handler already- try x++;.

Then you'll want to update some element with the new value. Try $('#someelement').html("You've pushed the button " + x + " times!");

See how far that takes you. :) Happy coding!

Upvotes: 1

Itay
Itay

Reputation: 16777

Use var instead of specifying a type like int (it's not supported in Javascript).

Also you had a redundant semicolon after your condition. I've commented it out.

Further more, you're not incrementing this variable anywhere in your code.

var x = 0;
$(document).ready(function(){

    $("#buttonid").click(function(){
        if(x == 0)  // Remove this - ;
        {
           $("#text").fadeIn();
           $("#othertext").fadeOut();
        }
        // Don't forget to increment the variable, with code like: x++;
    });
});

Upvotes: 2

Related Questions