Reputation: 25
I'd like to make an if / else statement in jquery with an alert box popping up and depening on what I choose the background color of the div should change.
ie)
I have a status light, when I press it, I get an alert, if I press OK it changes color to something else and if I press Cancel, the color is unchanged.
How do I do that?
Thanks in advance.
This is how the code looks right now,
HTML
<div id="checklistItem">
<div class="status1">
<p class="item1"> Sample item </p>
</div>
<div class="itemInfo1"></div>
</div>
CSS
.status1{
height:15px;
width:15px;
border-radius:15px;
background:red;
position:relative;
top:20px;
left:10px;
cursor:pointer;
}
Jquery
$(document).ready(function() {
$('.status1').click(function(e) {
e.preventDefault();
if (window.confirm("Are you sure?")) {
}
});
});
Upvotes: 0
Views: 1978
Reputation: 128791
First off, welcome (back) to StackOverflow and thank you for editing more detail into your question!
The solution to this is pretty straightforward. The if
statement surrounding the window.confirm
dialog determines what the user selected. If the result is true
, the user selected "Ok", otherwise the user selected "Cancel". You can read more about this on the Mozilla Developer Network.
From this we can change the background accordingly:
$('.status1').click(function(e) {
e.preventDefault();
/* Hold $(this) in a variable to prevent having to recall it.
* Here $this is equal to the element which has been clicked on.
*/
var $this = $(this);
if (window.confirm("Are you sure?")) {
/* If the user selected "Ok", change the background to green. */
$this.css({backgroundColor: '#0f0'});
}
else {
/* Otherwise the user selected "Cancel", change the background to red. */
$this.css({backgroundColor: '#f00'});
}
});
A better solution would be to simply introduce a new CSS class:
.confirmed {
background: #0f0; /* Green background. */
}
Then use jQuery's toggleClass()
method to add or remove the class depending on whether the user selected Ok or Cancel:
$this.toggleClass('confirmed', window.confirm("Are you sure?"));
The toggleClass()
method accepts a boolean value (true
or false
) as its second parameter, and we are supplying that through our window.confirm()
. 'confirmed'
is the name of the class we're adding or removing.
Upvotes: 1