简体   繁体   中英

using jquery to hide / show links based on checkbox

I know this is a common question on this forum, but I can not find the solution specific.

What I am trying to do is dynamically display HTML links based on checkbox selections. I'm having trouble figuring out what I'm doing wrong, the code does not seem to do anything at this point.

Below is the code.

<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta name="description" content="GIT Courses" />

<title>GIT Courses</title>
<link href="courses3.css" rel="stylesheet" type="text/css">
<!-- We include the jQuery CSS, API, and UI from CDN in the Head -->
<!-- Most browsers have CDN fed libraries already in cache, as they are used very frequently  -->
<!-- This will speed up load times, reduce bandwidth use, and serve from closest geographical servers -->
<!-- Ref: http://stackoverflow.com/questions/2180391/why-should-i-use-googles-cdn-for-jquery -->
<link
    href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css"
    type="text/css" rel="Stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.js"
    type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"
    type="text/javascript"></script>

</head>

<body>



    <div id="wrapper">

        <header>

            <div class=" headleft"></div>
            <div class="headright">
                <h1>Graphic Information Technology</h1>
            </div>

            <!-- end header -->
        </header>

        <nav>
            <table class="navigation">
                <thead>

                    <tr>
                        <th><a href="new2.html">home</a></th>
                        <th><a href="courses3.html">courses</a></th>
                        <th><a href="resources.html">resources</a></th>
                        <th><a href="labs.html">lab</a></th>
                    </tr>

                </thead>

            </table>

            <!-- end nav -->
        </nav>

        <!-- Begin HTML elements -->
        <h3>Thank you for your interest in our Developer courses!</h3>
        <p>Please select which campus resources you would like to explore
            more below:</p>
        <!-- Here is a "Field set" Array for the Resource Check Boxes -->
        <!-- We will leave the links out of the labels at this stage -->
        <fieldset id="checkboxArray">
            <legend>ASU Resources</legend>
            <label><input type="checkbox" name="rescheck[]"value="Career Preparation" />Career Preparation</label> 
            <label><input type="checkbox" name="rescheck[]" value="College Advising" />College Advising</label> 
            <label><input type="checkbox" name="rescheck[]"value="Counseling Services" />Counseling Services</label>
            <label><input type="checkbox" name="rescheck[]" value="Financial Aid" /> Financial Aid </label>
            <label><input type="checkbox" name="rescheck[]"value="Fitness &amp; Recreation" /> Fitness & Recreation </label> 
            <label><input type="checkbox" name="rescheck[]" value="Health Services" /> Health Services </label> 
            <label><input type="checkbox" name="rescheck[]"value="Housing" /> Housing </label>
            <label><input type="checkbox"name="rescheck[]" value="Library" /> Library </label>
            <label><input type="checkbox" name="rescheck[]" value="Parking" /> Parking </label> 
            <label><input type="checkbox" name="rescheck[]" value="Scholarships" /> Scholarships </label>
            <label><input type="checkbox" name="rescheck[]" value="Student Employment" /> Student Employment </label>
            <label><input type="checkbox" name="rescheck[]" value="Student Organizations" /> Student Organizations </label> 
            <label><input type="checkbox" name="rescheck[]" value="Tutoring Support" /> Tutoring Support </label>
            <label><input type="checkbox" name="rescheck[]" value="Writing Support" /> Writing Support </label>
        </fieldset>

        <!-- Here we display the resources selected.
     One way (well the only way I know how) is to Toggle visibility of DIVs based on selection. 
     The toggle is done within jQuery, here is the HTML side of it.
     Maybe not the best practice but it works, I never did take any classes on any of this :) -->

        <div class="myResources">
            <p>Here are the links to your selected resources:</p>
            <div  class="resource" resource-label="Career Preparation">
                <a href="https://students.asu.edu/careerguide/careerpreparation">Career
                    Preparation</a>
            </div>
            <div  class="resource" resource-label="College Advising">
                <a href="https://technology.asu.edu/advising">College Advising</a>
            </div>
            <div  class="resource resource-label="Counseling Services">
                <a href="https://students.asu.edu/counseling">Counseling
                    Services</a>
            </div>
            <div  class="resource" resource-label="Financial Aid">
                <a href="https://students.asu.edu/financialaid">Financial Aid</a>
            </div>
            <div  class="resource"
                resource-label="Fitness &amp; Recreation">
                <a href="http://fitness.asu.edu/">Fitness & Recreation</a>
            </div>
            <div  class="resource" resource-label="Health Services">
                <a href="https://students.asu.edu/health">Health Services</a>
            </div>
            <div  class="resource" resource-label="Housing">
                <a href="http://housing.asu.edu/home">Housing</a>
            </div>
            <div  class="resource" resource-label="Library">
                <a href="http://lib.asu.edu/">Library</a>
            </div>
            <div  class="resource" resource-label="Parking">
                <a href="https://cfo.asu.edu/pts">Parking</a>
            </div>
            <div  class="resource" resource-label="Scholarships">
                <a href="https://students.asu.edu/scholarships">Scholarships</a>
            </div>
            <div  class="resource" resource-label="Student Employment">
                <a href="https://students.asu.edu/employment">Student Employment</a>
            </div>
            <div  class="resource" resource-label="Student Organizations">
                <a href="http://asu.orgsync.com/">Student Organizations</a>
            </div>
            <div  class="resource" resource-label="Tutoring Support">
                <a href="https://studentsuccess.asu.edu/">Tutoring Support</a>
            </div>
            <div  class="resource" resource-label="Writing Support">
                <a href="https://studentsuccess.asu.edu/writingcenters">Writing
                    Support</a>
            </div>

            <!-- end of content wrapper -->
        </div>
        <!--  End of HTML Elements -->
        <!--  Suggested best practice is to put all Scripts at the bottom of the page, just before the End of Body Tag -->
        <!--  This is to speed up page loading time -->
        <!--  Ref: http://stackoverflow.com/questions/2105327/should-jquery-code-go-in-header-or-footer -->
        <!-- jQuery code begins here -->
        <script type="text/javascript">
    // We place all jQuery code inside this "Document Ready" handler to ensure everything loaded completely before running code
    $(document).ready(function() {
        // bind to click function
        $('input[type="checkbox"]').click(function() {
            // test if any are checkboxes in the array are checked
            if ($('input[name="rescheck[]"]:checked').length > 0) {
                // hide all resources until...
                $('.resource >div').hide();
                // we loop checked boxes and show div.
                $("input[name='rescheck[]']:checked").each(function() {
                    $('.resource >div[resource-label=' + this.id + ']').show();
                });
                // hmm... at least that was the idea
                //FIXME: Why didn't this hide?
            } else {
                // none checked - hide all
                $('.resource >div').hide();
            }
        });​​
    }); 
</script>
    </div>
</body>
</html>

You should use Attribute Starts With Selector [name^="value"]

$('input[name^="rescheck"]:checked')

Your code should be like this:-

$('.resource').hide();
$('input[type="checkbox"]').click(function() {
    $("input[name^='rescheck']").each(function() {
        if ($(this).is(":checked"))
            $('div[resource-label="'+this.value+'"]').show();
        else
            $('div[resource-label="'+this.value+'"]').hide();
    });
});

Refer LIVE DEMO

You have a few errors in your HTML, I dont know if these are typos in your actual script or errors whilst formatting here but this line needs sorting out:

<div  class="resource resource-label="Counseling Services">

Notice the resource-label is part of the elements class attribute currently.

You could try something along these lines for your jQuery to make it a little simpler for you.

$('#checkboxArray').on('click', 'input[type="checkbox"]', function(event)
{
    var resources = $('.myResources');

    // Hide all resources
    resources.children('div').hide();

    // Cycle through the checkboxes siblings
    $(this).siblings().each(function(index)
    {
        // If they are checked show the resource
        if ($(this).is(':checked') 
        {
            resources.find('div[resource-label="' + $(this).val() + '"]').show();
        }
    });
}

if the checkboxes are in the same order of the related div's, use the element index as reference.

$('input[name^="rescheck"]').click(function() { // if checkbox clicked
  var index = $(this).parent().index(); // gets parent index since nested in label
  $('.resource:eq(' + index + ')').toggle() // hide or show related div
});

check out this fiddle

Every one of the responses provided here deserves an up vote or few. Thank you, I haven't had a chance to test the codes yet, but the examples and suggestions are very helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM