Reputation: 294
I have a <div>
I'm clicking on to change the value of a variable. The variable changes but the if(oneorzero == 0)
never works. It always continues to == 0
. Even though the variable is different, it still acts the same. What am I doing wrong?
Edit:
I left a part out. After I change the variable, I need to check the onmousedown function to see if it worked. This is my issue.
var oneorzero = 0;
var onmousedownfunction= function() {
if(oneorzero == 0){
alert('One or Zero equals 0');
//Do something
};
if(oneorzero == 1){
alert('One or Zero equals 1');
//Do something
};
};
$('.class').click(function(){
val_class = $(this).attr('value');
if(val_class == '0'){
$(this).attr('value','1');
oneorzero = 1;
};
if(val_class == '1'){
$(this).attr('value','0');
oneorzero = 0;
};
});
$(canvas).mousedown(onmousedownfunction);
Upvotes: 2
Views: 100
Reputation: 55750
Place that inside the click event.
The way you have written will only execute once when the page loads.
Also use console.log
instead of alert
as it is a lot more elegant;
Also you can use parseInt
and eliminate an extra variable using it
$('.class').click(function () {
var val_class = parseInt($(this).attr('value'), 10),
oneorzero;
if (val_class === 0) {
oneorzero = 1;
} else if (val_class == 1) {
oneorzero = 0;
}
$(this).attr('value', oneorzero );
console.log(val_class);
});
The same can be written in a single line and can eliminate the if else
completely by using a ternary operators
$('.class').click(function () {
var $this = $(this),
val_class = parseInt($(this).attr('value'), 10) === 0 ? 1 : 0 ;
$(this).attr('value', val_class).text(val_class);
console.log(val_class);
}).click();
Upvotes: 2
Reputation: 16263
Split the conditions inside the listener with an else
, or the flow will always fall through to the second condition:
if (val_class == '0') {
$(this).attr('value', '1');
oneorzero = 1;
} else if (val_class == '1') { // no 'else', and we'd be setting 'value' again
$(this).attr('value', '0');
oneorzero = 0;
}
Upvotes: 1