Manipulating Div Content with JQuery Based on Checkbox Selections

My goal is to extract content from a hidden div that contains an unordered list with specific classes and move certain list elements into placeholder divs based on checkbox values.

Initially, when no checkboxes are checked, I want all list elements in the hidden div to be displayed in the placeholder divs.

When checkboxes are selected, I want to transfer only those list elements from the hidden div whose classes correspond to the checkbox values into the placeholder divs. List elements in the hidden div without matching checkbox values should remain hidden.

Below is the HTML code:

<div id="php_hidden_results">
<ul id="vv_bg_results">
    <li class="Sauces_Dips_Spreads Latin">Chili Lime Sour Cream</li>
    <li class="Main_Dish Latin">Carnitas</li>
</ul>

<ul id="vv_content_wrapper_results">
    <li class="Sauces_Dips_Spreads Latin"><div class="vv_content" id="content1">
        <h2><a href="/v1.0/recipes/show_recipe.php?idrecipe=22">Chili Lime Sour Cream</a></h2>
        <div class="vv_content_box">
            <div class='subtitle'>Sauces Dips Spreads: Latin</div>
        </div>
    </li>

    <li class="Main_Dish Latin"><div class="vv_content" id="content2">
        <h2><a href="/v1.0/recipes/show_recipe.php?idrecipe=21">Slow Cooker Carnitas</a></h2>
        <div class="vv_content_box">
            <div class='subtitle'>Main Dish: Latin</div>
        </div>
    </li>
</ul> 
</div>

<div id="test">Replace with checked value</div>

<div class="filterContainerBody">              
<b>RECIPE TYPES</b><br />
<div class="horzRule"></div>
<ul class="checkfilter">
    <li><input type='checkbox' value='Sauces_Dips_Spreads' />Sauces Dips Spreads</li>
    <li><input type='checkbox' value='Main_Dish' />Main Dish</li>                
</ul>
<b>CUISINE TYPES</b><br />
<div class="horzRule"></div>                
<ul class="checkfilter">
    <li><input type='checkbox' value='Latin' />Latin</li>                
</ul>
</div><!-- end of filterContainer -->

<div id="vv_bg" class="vv_bg">   
   <ul class="results">
        <li></li>            
    </ul>
</div>

<div id="vv_content_wrapper" class="vv_content_wrapper">
    <ul class="results">
        <li></li>
    </ul> 
</div>

The CSS code:

#php_hidden_results
{
    display: none;
}

.filterContainerBody
{
    width: 240px;
    display: block;
    background-color: #ffbb00;
}

Jquery script:

$(document).ready(function() {
$("ul.checkfilter :checkbox").click(function() {
    var divhidden_bg_li = $('#php_hidden_results ul#vv_bg_results li');
    $(".checkfilter :checkbox:checked").each(function(){
        var filtervalue = $(this).val();
        var filterclass = $(divhidden_bg_li).filter(filtervalue);
        var divhidden_bg= $('#php_hidden_results ul#vv_bg_results').children("." + filtervalue);
        $('#vv_bg ul.results').html(divhidden_bg); 
        var divhidden_content = $('#php_hidden_results ul#vv_content_wrapper_results').children("." + filtervalue);
        $('#vv_content_wrapper').html(divhidden_content);                               
    });   
});
});

This Jquery script does not show all list elements initially or when no checkboxes are selected. It retrieves specific list elements from the hidden div upon the first check but becomes unresponsive. For more information and troubleshooting, see http://jsfiddle.net/Ayjent/ddsjB/5/

I am considering using AJAX for continuous server calls to avoid potential placeholder issues. Any assistance or guidance would be highly appreciated.

Answer №1

Why not give this example a shot:

$(document).ready(function() {
$('input:checkbox').change(
            function(){
        var vv_bg = $('.vv_bg').find('.'+$(this).val()).html();
        var vv_content = $('.vv_content_wrapper').find('.'+$(this).val()).html();
                if ($(this).is(':checked') && (vv_bg != null && vv_content != null)) {
                    $('<li>'+vv_bg+'</li>').attr('class',$(this).val()).appendTo('#result_vv_bg ul');   
            $('<li>'+vv_content+'</li>').attr('class',$(this).val()).appendTo('#result_vv_content_wrapper ul');
                }
                else {
                    $('#result_vv_bg li:contains('+$(this).val()+')').remove();
            $('#result_vv_content_wrapper li:contains('+$(this).val()+')').remove();    
                }
            });     
});

Fiddle -> Fiddle

Answer №2

To improve the functionality of the jQuery function and HTML structure, I made significant changes by removing the hidden div and placeholder div. I utilized the delegate(), appendTo(), empty(), and detach functions in the following manner:

HTML

<div class="filterContainerBody">
<b>RECIPE TYPES</b><br />
<div class="horzRule"></div>
<ul class="checkfilter">
    <li><input type='checkbox' value='Sauces_Dips_Spreads' />Sauces Dips Spreads</li>
    <li><input type='checkbox' value='Main_Dish' />Main Dish</li>                
</ul>
<b>CUISINE TYPES</b><br />
<div class="horzRule"></div>                
<ul class="checkfilter">
    <li><input type='checkbox' value='Latin' />Latin</li>                
</ul>
</div><!-- end of filterContainer -->

<div id="vv_bg" class="vv_bg">   
<ul class="results">
    <li class="Sauces_Dips_Spreads Latin">Chili Lime Sour Cream</li>
    <li class="Main_Dish Latin">Carnitas</li>          
</ul>
</div>

<div id="vv_content_wrapper" class="vv_content_wrapper">
<ul class="results">
    <li class="Sauces_Dips_Spreads Latin"><div class="vv_content" id="content1">
        <h2><a href="/v1.0/recipes/show_recipe.php?idrecipe=22">Chili Lime Sour Cream</a></h2>
        <div class="vv_content_box">
            <div class='subtitle'>Sauces Dips Spreads: Latin</div>
        </div>
    </li>

    <li class="Main_Dish Latin"><div class="vv_content" id="content2">
        <h2><a href="/v1.0/recipes/show_recipe.php?idrecipe=21">Slow Cooker Carnitas</a></h2>
        <div class="vv_content_box">
            <div class='subtitle'>Main Dish: Latin</div>
        </div>
    </li>
</ul> 
</div>

JQUERY:

var $lis_bg;
var $lis_content_wrapper;

$('.checkfilter').delegate('input:checkbox', 'change', function() {

if (!$lis_bg){ 
    $lis_bg = $('#vv_bg ul.results > li').detach();
    $lis_content_wrapper = $('#vv_content_wrapper ul.results > li').detach();
};
$('#vv_bg ul.results').empty();
$('#vv_content_wrapper ul.results').empty();

if ($('input:checked').length == 0) {
    $lis_bg.appendTo('#vv_bg ul.results');
    $lis_content_wrapper.appendTo('#vv_content_wrapper ul.results');
    $lis_bg = null;
    $lis_content_wrapper = null;
} else {
    $('input:checkbox').each(function(i, chk) {
        if (chk.checked) {
            $lis_bg.filter('.' + $(chk).attr('value')).appendTo('#vv_bg ul.results');
            $lis_content_wrapper.filter('.' + $(chk).attr('value')).appendTo('#vv_content_wrapper ul.results');
        } 
    });

}
});​

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JQuery does not recognize $(this) after the HTML has been altered

I manage a website that includes several href links and 2 buttons that have the ability to modify those links dynamically. <div class="links"> <p class="hlCategory">Classical Mechanics</p> <ul> <li><a cl ...

Issues with jQuery Ajax

Hello all, I've come across this snippet of jquery code: <script type="text/javascript" > $(function() { $(".submitButton").click(function() { var post = $("#post").val(); var dataString = 'post='+ ...

Using jQuery .animate() leading to erratic input movements

I am currently utilizing jQuery's .animate() feature to create a smooth animation effect on the width of a <div> element when a child <input> is in focus. Nevertheless, I'm encountering an issue where the input field jumps up and down ...

Which specific jQuery functionality was made visible?

When it comes to jQuery, how is it exposed? // Expose jQuery to the global object window.jQuery = window.$ = jQuery; However, there are in fact two versions of jQuery: var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( s ...

Manually incorporating multiple React components into a single container

I am currently in the process of upgrading an old JavaScript application that relies heavily on jQuery by introducing some React components. The existing code utilizes JS/jQuery to dynamically add elements to the DOM, and I am looking for a way to replace ...

The elastic image slideshow maintains the original size of the images and does not resize them

When utilizing the elastic image slider, I encounter a similar issue as described at Elastic Image Slideshow Not Resizing Properly. In the downloaded example, resizing the window works correctly. However, when trying to integrate the plugin with Twitter B ...

Tips for Implementing the jquery.Validate Plugin with a jquery.multiselect Dropdown

Let's talk about a predicament I'm facing: trying to integrate a dropdown box into a form that already makes use of the jquery.validate plugin along with other fields that currently validate correctly. The dropdown box is being added using the jq ...

conceal the mustard-colored dots within the overlay

Whenever I trigger the link, a modal window pops up, but it comes with an unwanted black background color and yellow dots. How can I prevent the yellow dots from showing up on the overlay? http://jsfiddle.net/y88WX/18/embedded/result/ <nav class="da-d ...

Refresh a Div using JSON content with Struts2 Jquery Plugin

Is there a way to dynamically reload the content of a div with just a specific part of a JSON object in it? The code provided works perfectly, but it displays the entire JSON object within curly braces. I want only one variable from the object to be shown ...

Chrome is not storing the CSS file in its cache memory. However, it is successfully caching .js and .png

I have noticed that the CSS file is not being cached in the Chrome browser. My application is created using Angular-CLI and all the necessary cache-control headers are set, with an Expires header of 5 minutes: Accept-Ranges:bytes Cache-Control:max-age=600 ...

CSS - Layering <divs> on top of clear <div>'s

Is there a method to eliminate the transparency of content/images within a <div> that is transparent? Below is the provided HTML: <div id="main-button-wrapper" class="left"> <div id="button-bg-layer" class="box-bg-layer corner ...

Is it possible to preload numerous extensive datasets in the background using ajax?

I'm currently in the process of developing a web application that operates solely on one page and revolves around presenting various table data in grids. There are approximately 30 different tables stored in the database, with any of them being access ...

Tips for resolving flickering animations in CSS and JavaScript

Is it possible to dynamically set a scale and margin for an element in order to center it fluidly using the wheel event? I am aiming to achieve a smooth transition while also adjusting scroll position on the wrapping element in a fluid manner. In the prov ...

Verify if a fresh message has been added using AJAX

Is it possible to create a notification system similar to Facebook, where the tab title displays the number of new messages without refreshing the entire page? Below is a snippet of code from my website's message box feature that I am working on. < ...

Using a single form, the rest of the form fields are restricted when uploading images with Ajax

I am facing a challenge with uploading an image using ajax. I have other fields in the form that require validation before submission is allowed. However, whenever I try to upload an image, all the fields in the form show errors. $('#my_thumbnail&apo ...

The error message being displayed states that 'null' cannot be used as an object when evaluating 'response.productType'

Hey everyone, I'm fairly new to working with Ajax and I've encountered an error in my code that says: TypeError: 'null' is not an object (evaluating 'response.productType'). I'm not sure why this is happening. Below is th ...

lengthy conditional statement in JavaScript

Is there a more efficient way to handle a long series of if-else statements in JavaScript? I'm not experienced enough with the language to optimize this code. Any suggestions or guidance would be greatly appreciated. $('#webform-component-primar ...

Tips for Positioning a Page Layout in the Center Using HTML and CSS

I'm a beginner in HTML and CSS and I'm trying to create a simple webpage layout from scratch. I want all the elements of the page (nav, header, section, footer, etc.) to be centered while still keeping the nav bar on the left side. I've set ...

Experience the combined power of addthis, isotope, and nicescroll - all in a single

I am utilizing a WordPress template that includes a set of share buttons from AddThis. <ul class="addthis extra"> <li class="addthis-hold"> <div class="addthis_toolbox" addthis:url="<?php the_permalink( ...

The Ajax request is exceeding its limits

$(function(){ var imgClass = $('.caruselWrap').find('img'); imgClass.eq(1).addClass('pro'); var hasPro = $('.caruselWrap').find('img.pro'); var count = 3; // "position" of images, security for not breakin ...