0

I am currently tackling some JQuery and Javascript and I have encountered a small problem that I can't for the life of me figure out how to solve.

I have a form which dynamically loads information from a json file which re-uses a "wpTemplate" and populates a select list. This form compromises something of the following;

 <div class="wp" id="wpTemplate" >
    <input type="checkbox" id="wpCheck" name="" class="wp" value="">
    <label id="wpLabel" class="wpLabel"></label>

    <div class="uc" id="uc">
       <select class="ucSelect" id="ucSelect" name="case" multiple>
          <option id="option" class="option"></option>
       </select>
    </div>
 </div>

In essence, there could be multiple div "wpTemplate". My aim is to somehow have the ability to select either one or many "wpCheck" checkbox and for the "uc" div to display depending on the specific checkbox being selected.

I tried adding style="display: none;" to the "uc" class and a simple if-else statement with the show/hide functionality but to no avail.

$('.wp').each(function() {
   if($(this).is(":checked")) {
      $('.uc').show();
   } else {
      $('.uc').hide();
   }
});

I'm new to JQuery so any help or alternative ways would be much appreciative.

3
  • 1
    can you show some actual code and maybe comments on where you are having issues? Commented Aug 10, 2016 at 19:31
  • 1
    Better replace id wpTemplate with class: id must be unique on the page. Commented Aug 10, 2016 at 19:42
  • I made you a jsfiddle jsfiddle.net/L0bco1h5/4. I changed your ids to classes because it have to be unique. I hope this will help you. Commented Aug 10, 2016 at 19:50

2 Answers 2

2

How about:

$('.wpCheck').on('change', function () {
  var $uc = $(this).closest('.wpTemplate').find('.uc')
  if ($(this).prop('checked')) {
    $uc.show()
  } else {
    $uc.hide()
  }
})

Here's a working fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

Here is another way:

$( document ).ready(function() {
    $('input.wp').change(function() {

        var $this = $(this);
        if ($this.is(":checked"))
        {
            $this.siblings('div.uc').show();
        }
        else
        {
            $this.siblings('div.uc').hide();
        }
        });
    });

fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.