0

I need a content filtering system for my website. By checking and unchecking of a checkbox, the according elements should be shown or hidden.

<form>
  <p><input type="checkbox" checked="checked"><label>Plants</label></p>
  <p><input type="checkbox" checked="checked"><label>Animals</label></p>
  <p><input type="checkbox" checked="checked"><label>Humans</label></p>
</form>

The checkboxes above should toggle the visibility of the divs below with the according class, by changing display:block; to display:none;

<div class="Plants" style="display:block">
  <p>Grass</p>
<div>
<div class="Humans" style="display:block">
  <p>John</p>
<div>
<div class="Plants" style="display:block">
  <p>Flower</p>
<div>
<div class="Animals" style="display:block">
  <p>Lion</p>
<div>

For example: By uchecking the Plants checkbox, the divs with Grass and Flower should be hidden.

What would be the most elegant way to accomplish that in php or javascript?

1 Answer 1

1

According to your HTML structure you may use:

As reported in the comment:

In your PHP file you have to include the jQuery library. The line you have to include is:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In order to add to your PHP file the jQuery function you have to add a <script> tag and inside it you must copy the jQuery function. It is not necessary to change the reaming part of your PHP file.

The snippet:

//
// When the document is Ready
//
$(function () {
  //
  // when you click a checkbox
  //
  $(':checkbox').on('change', function(e) {
    var divClass = $(this).next().text();
    $('.' + divClass).toggle(this.checked);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form>
    <p><input type="checkbox" checked="checked"><label>Plants</label></p>

    <p><input type="checkbox" checked="checked"><label>Animals</label></p>

    <p><input type="checkbox" checked="checked"><label>Humans</label></p>
</form>

<div class="Plants" style="display:block">
    <p>Grass</p>
</div>
<div class="Humans" style="display:block">
    <p>John</p>
</div>
<div class="Plants" style="display:block">
    <p>Flowesr</p>
</div>
<div class="Animals" style="display:block">
    <p>Lion</p>
</div>

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

2 Comments

Since I am pretty new to scripting, could you explain how this works and how this snippet can be implemented in the php, please.
@GabrielWinkler I updated the answer. I hope this could help you.

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.