Junaid Malik Junaid Malik - 11 months ago 33
CSS Question

Else Condition not working java script / jquery

I'm new here, can someone please help me...
i have 2 div's #main and #side.

In my #main div i have few check boxes ,

on checked event, i apend my check box label into #side div and add/remove some classes and it's working perfectly

but when i unchecked my input, it's not working not add/remove classes or apend to #main div

here is my code

$('input[type="checkbox"]').change(function() {

if (this.checked) {
{ // This condition not working //

Thanks in Advance

Here is a full code.

Answer Source

First, since you're using jQuery, I suggest you do not use this.checked, but $(this).is(':checked').

However, the reason your code is not working in reverse is because you're moving the .next('label') in DOM on checking the checkbox. So, on unchecking, .next('label') won't exactly return the label, as it is has been moved.

This is how I'd write your function:

$('input[type="checkbox"]').on('change', function(){
  var label = $('label[for="'+$(this).attr('id')+'"]'),
      checked = $(this).is(':checked');
  label.toggleClass("icon icon-active").appendTo(checked?'#side':'#main')

Now, another problem with your script is that, on return, it appends the labels to the end of the div, instead of after the checkboxes. To fix that, here's what you should use:

$('input[type="checkbox"]').on('change', function(){
  var label = $('label[for="'+$(this).attr('id')+'"]'),
      checked = $(this).is(':checked');
  label.toggleClass("icon icon-active")[

Updated your fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download