I'm trying to make a boolean change in this value by using a function. I tried it this way:
var itemInStock = false;
$("#button").click(function(){
itemInStock = true
}
if( itemInStock === false){
document.write("item is out of stock");
} else{
document.write("item is in stock");
}
I understand why it's not working but I can't find a way to solve this!
I'm trying to make a boolean change in this value by using a function. I tried it this way:
var itemInStock = false;
$("#button").click(function(){
itemInStock = true
}
if( itemInStock === false){
document.write("item is out of stock");
} else{
document.write("item is in stock");
}
I understand why it's not working but I can't find a way to solve this!
item is out of stock
.
– PeeHaa
Commented
Jan 15, 2013 at 20:20
I just can guess what you're trying to achieve. It seems like you wanna check at some point, if item is currently in stock. Since you can't know when the click will occur, one solution could be periodically checking the value.
(function () {
var itemInStock = false;
$("#button").click(function () {
itemInStock = true
});
window.setInterval(function () {
if (itemInStock === false) {
console.log("item is out of stock");
} else {
console.log("item is in stock");
}
}, 500);
})()
http://jsfiddle/Ttu5N/
Tell me, if I'm wrong with my guessing.
Update: way easier approach
$(function () {
var $state = $('#state');
$state.text('item is out of stock');
$("#button").click(function () {
$state.text('item is in stock');
});
})
<button id="button">click me</button>
<div id="state"></div>
http://jsfiddle/Wb3ET/ Just do it directly on click.
because itemInStock doesn't get changed until the button is clicked...
You cannot use document.write after load and is also not necessary also the Boolean changes when the button is clicked and not before
Create a span with id="status" and have
var itemInStock = false;
$(function() {
$("#button").click(function(){
itemInStock = true;
$("#status").html("item is in stock":
}
$("#status").html(itemInStock?"item is in stock":"item is out ofstock");
});
// HTML
<div id="status">item is out of stock by default</div>
// JS
var itemInStock = false;
$("#button").click(function(){
itemInStock = true;
}, changeStatus());
function changeStatus(){
if( itemInStock === false){
$('#status').html("item is out of stock");
} else{
$('#status').html("item is in stock");
}
}