ramoncis
ramoncis

Reputation: 29

jQuery perform function if checkbox is selected

I am having an issue creating two sets of check boxes that act independently of each other. Checking off any of the options aside from N/A should cause an input field to appear below each set. However, the second set of check boxes only produce an input field when I check off one of the options from the first set followed by N/A (Set to make the input field disappear.) How can I condense the script below and make it fully functional?

function checkChecked (){
  if($(".needID").is(':checked')) {
    $('.hideOnLoad').show().focus();
    $( ".selectNone" ).prop( "checked", false );

  }
  else {$('.hideOnLoad').val("").hide();}

  if($(".needID2").is(':checked')) {
    $('.hideOnLoad2').show().focus();
    $( ".selectNone2" ).prop( "checked", false );

  }
  else {$('.hideOnLoad2').val("").hide();}
}

$( "input.needID").on("click", checkChecked );
$( "input.selectNone" ).on("click", function() {
  if($(".selectNone").is(':checked')) {
    $( ".needID" ).prop( "checked", false );
    checkChecked ();
  }

  $( "input.needID2").on("click", checkChecked );
  $( "input.selectNone2" ).on("click", function() {
    if($(".selectNone2").is(':checked')) {
      $( ".needID2" ).prop( "checked", false );
      checkChecked ();
    }   

  });

});
checkChecked ();

https://jsfiddle.net/of0h2c17/1/

Upvotes: 0

Views: 36

Answers (1)

isherwood
isherwood

Reputation: 61083

You're not properly closing this:

$( "input.selectNone" ).on("click", function() {

Therefore, the next click function is wrapped inside it.

Fixed demo

Good code formatting saves many headaches. The JSfiddle TidyUp button makes it immediately clear what the problem is.

Upvotes: 1

Related Questions