Reputation: 187
If I do a click based on id a border and background color is added. If I do another click based on id of button it should change the border and background color to another color but the click for button is not working to change color from green to black. I can't figure why. My code snippet is below. The if statement is never evaluated.
Thank You In Advance
if ($(".g_card").on('click', function() {
$('#addon_1').addClass('baddon_1add');
$("#gift_occasion").toggle();
}));
if ($("#work").on('click', function() {
alert("button not working");
$('#addon_1').removeClass('baddon_1add').addClass('.baddon_1');
}));
.baddon_1 {
border: solid 1px #808080;
background-color: #FFFFFF;
}
.baddon_1add {
border: solid 2px #2D6E20;
background-color: #EFF7ED;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="g_card">
<input type='button' id="work" value='-' class='qtyminus' field='quantity' />
<input type='text' id="g_quantity" name='quantity' value='0' class='qty' />
<input type='button' id="some_occasion" value='+' class='qtyplus' field='quantity' />
<br />
<div id="gift_occasion" style="display:none">
<select>
<option>Occasion</option>
</select>
</div>
</div>
Upvotes: 1
Views: 59
Reputation: 13304
$(".g_card").on('click', function() {
$('#addon_1').addClass('baddon_1add');
$("#gift_occasion").toggle();
});
$("#work").on('click', function(e) {
e.stopPropagation();
$('#addon_1').removeClass('baddon_1add').addClass('baddon_1');
});
.baddon_1 {
border: 1px solid #808080;
background-color: #FFFFFF;
}
.baddon_1add {
border: 2px solid #2D6E20;
background-color: #EFF7ED;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="g_card">
<input type='button' id="work" value='-' class='qtyminus' field='quantity' />
<input type='text' id="g_quantity" name='quantity' value='0' class='qty' />
<input type='button' id="some_occasion" value='+' class='qtyplus' field='quantity' />
<br />
<div id="gift_occasion" style="display:none">
<select>
<option>Occasion</option>
</select>
</div>
</div>
<div id="addon_1">I added this div to with ID addon_1.</div>
I do not know exactly where #addon_1
is supposed to be. But I think your problem lays with event propagation. I've added e.stopPropagation()
to your minus button event handler. This prevents the event from bubbling up and executing the click handler on the parent. See the result in the snippet.
I also deleted the IF
s around the event handler setters, they are pointless in this context. This piece of code is responsible for the canceling of the bubbling.
function(e) {
e.stopPropagation();
}
The event passes it's event object as an argument, we reference it via e
. We call stopPropagation
, to stop the event bubbling up.
General lesson:
If you set multiple click handlers on the parent and the childs use
event.stopPropagation()
to run an event on the child, but not on the parent.
Upvotes: 1