-2

I'm having trouble understanding why my second code here doesn't work (Ruhetag 2 which has just been edited). As a test to see if my targeting was ok I wrote Ruhetag1, which works find when clicking my checboxes, but I then wrote Ruhetag2 to also have the same function but in addition check to see which checkboxes were already checked on entry. Ruhetag1 works fine, Ruhetag2 isn't reacting at all - it's not giving me an error message either. Can you help me see where this is fallong down. Many thanks.

Ruhetag1

$(".quiet").click(function (e) {
    $(this).parent().find(".optimes input[type=text]").val('');
    $(this).parent().find(".optimes").toggle(); 
});

Ruhetag2

$(function(){   
    $(".quiet").each(function(){
        quiet(this);
    });
    $(".quiet").click(function() {
        quiet(this);
    });
});
function quiet() {
    if ($(this).is(':checked')) {
        $(this).parent().find(".optimes input[type=text]").val('');
        $(this).parent().find(".optimes").hide();
    } else {
        $(this).parent().find(".optimes").show();
    }
}
Rockwelpe
  • 21
  • 5

1 Answers1

0

The element isn't being passed to the function quiet(), so $(this) does not exist within the function. Try the below?:

$(function(){   
  $(".quiet").each(function(){
    quiet($(this));
  });
  $(".quiet").click(function() {
    quiet($(this));
  });
});

function quiet(elem) {
   var checkbox = elem;
       if (checkbox.is(':checked')) {
          checkbox.parent().find(".optimes input[type=text]").val('');
          checkbox.parent().find(".optimes").hide();
      } else {
          checkbox.parent().find(".optimes").show();
      }
}
Oli
  • 852
  • 6
  • 12