Reputation: 33
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!
Upvotes: 1
Views: 10647
Reputation: 10050
// 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");
}
}
Upvotes: 0
Reputation: 4457
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);
})()
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.net/Wb3ET/ Just do it directly on click.
Upvotes: 3
Reputation: 177691
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");
});
Upvotes: 0
Reputation: 23301
because itemInStock doesn't get changed until the button is clicked...
Upvotes: 0