Junaid Malik Junaid Malik - 9 months ago 28
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).next('label').removeClass("icon");
$(this).next('label').addClass("icon-active");
$(this).next('label').detach().appendTo('#side');
}
else
{ // This condition not working //
$(this).next('label').addClass("icon");
$(this).next('label').removeClass("icon-active");
$(this).next('label').appendTo('#main');
}
});


Thanks in Advance

Here is a full code.
http://jsfiddle.net/o8n1b8z1/4/

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")[
      checked?'appendTo':'insertAfter'
  ]($(checked?'#side':this));
})

Updated your fiddle