vendredi 3 mars 2017

How to show/hide content if a checkbox is checked or not

I have some jQuery that will show/hide a hidden div depending on the value that is selected in a dropdown field:

$('.hidden-content-here').hide();
$('select[name="my_field_name_here"]')
  .on('change', function() {
    var $this = $(this),
        selected = $this.find(':selected').val(),
        options = ['Yes'];

    $('.hidden-content-here').hide();
    if(options.indexOf(selected) > -1) {
      $('.my_field_name_here').toggle();
    }
  })
.trigger('change');

And here's the HTML:

<label>Hide/Unhide Hidden Content</label>
<select name="my_field_name_here">
 <option value="No">No</option>
 <option value="Yes">Yes</option>
</select>

<div class="hidden-content-here">
  <!--Hidden content here-->
</div>

This works fine - if the page loads and the dropdown field already has a value of 'Yes', then the hidden content will be displayed. If the page loads and the dropdown doesn't have a value of 'Yes', then the hidden content won't be displayed. And it will change when different values are selected.

My issue is that I need to change the field from a dropdown to a checkbox, but I can't figure out how to change the jQuery to work with this different type of field instead. The checkbox field will have a value of 'Yes' if it is checked and the HTML will look like this instead:

Hide/Unhide Hidden Content

Thanks for any help with this.




Aucun commentaire:

Enregistrer un commentaire