user4593252
user4593252

Reputation: 3506

What is causing my label's event handler to fire twice?

What happens:

Clicking the checkbox causes the code to fire once (as expected). Clicking the label causes the code to fire twice.

The code:

function ToggleVisibility(ctl) {
  console.info($(ctl).css("background-color"));
  var backgroundColor = $(ctl).css('background-color') === 'rgb(255, 255, 255)' ? 'rgb(255, 165, 0)' : 'rgb(255, 255, 255)';
  console.info(backgroundColor);
  $(ctl).css("background-color",
    backgroundColor);
  console.info($(ctl).css("background-color"));
  console.debug($(ctl));
  console.info("****");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divTemplate">
  <label onclick="ToggleVisibility(this)" style="background-color: white;"><input type="checkbox" /><span>Checkbox item</span></label>
</div>

What's going on here?

Upvotes: 0

Views: 51

Answers (1)

Praveeta Singh
Praveeta Singh

Reputation: 64

You need to add event.preventDefault(); to the start of the event handler.

Upvotes: 2

Related Questions