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

The modal popup is getting lost behind the slider

I am facing an issue with opening a Modal popup for customer details. The problem occurs when the modal opens behind a slider on the website. However, when I slide the page down, the content of the modal becomes fully visible. https://i.stack.imgur.com/wR ...

Elastic_Frame | "Error: Unable to process action as property 'toLowerCase' is not defined"

Attempting to create a personal and project portfolio using Vu Khanh Truong's "elastic_grid" jQuery plugin for the actual portfolio. You can access it here. However, encountering some issues on my page: 1) The header for the portfolio section disappe ...

Tips for keeping the background image in place while resizing the page

How can I set the background image for the whole page without it changing position with resizing? The image is 3065px in height so that should not be the issue. .bg { background-image: url("#"); height: 3065px; width: 100%; background-positio ...

What is the proper method for changing the height of this component in HTML?

Hey there! I'm brand new to HTML and I'm embarking on a little project for myself to enhance my skills. I have a question about adjusting the height of some text - I want it to look similar to Twitter, where each "tweet" is clearly separated from ...

When using the .after() method to add jQuery elements, keep in mind that they will not trigger any

Here is the snippet of code provided: <s:file name="upload" id="upload"></s:file> $('input[id^="upload"]').change(function(){ alert("aa"); $(this).after('<input type="file" name="upload_3" id="upload_3"/> ...

Specify the width of one element to always be the same as the width of another

One common challenge is maintaining the width of one element equal to another when the page loads (refer to link description here). However, it becomes tricky when the side width changes, such as resizing the browser window. Is there a way to dynamically ...

Pair objects that possess a specific attribute

I have a HTML snippet that I want to modify by adding the CSS class HideEdit to hide specific columns. <th class="rgHeader" style="text-align: left;" scope="col" _events="[object Object]" control="[object Object]" UniqueName="Edit"> This particular ...

How can you hide specific elements in HTML/CSS based on window size without relying on media queries?

How can I create an HTML/CSS toolbar where specific elements disappear completely when the browser size is decreased, similar to how the favorites bar functions in most browsers? The toolbar should be able to display a varying number of items. In this cas ...

Error: The function indexOf() is not supported by the selected element

I'm currently working on a program that involves copy and paste functionality. However, whenever I attempt to click on the box, an error pops up saying: Uncaught TypeError: $(...).indexOf is not a function. I attempted to use .contains as an alternat ...

Activate month input programmatically

Having an issue trying to open a month popup using jQuery trigger. I have a button and an input of type month, but when the button is clicked, the popup does not open as expected. You can find the fiddle for this question here. $(document).ready(functio ...

Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this: "document.body.style.fontSize = 100/50/20" However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for ...

difficulty with parsing JSON in jQuery when referencing an external file containing the same data

Looking for help with parsing a json file using jquery? Check out this working sample: http://jsfiddle.net/bw85zeea/ I'm encountering an issue when trying to load "data2" from an external file. The browser keeps complaining that it's an invalid ...

Equal-height columns in a responsive grid system

I'm currently facing an issue with a layout that seems simple I am working on a design featuring 4 headline boxes. In the "desktop" view, all 4 boxes need to be of equal height. The same applies when viewed across 2 boxes in the "tablet" mode. Howeve ...

Steady Content of a Parallax Webpage

Hey there! I recently put together this awesome site and I'm facing a challenge with fixing text on the first slide, specifically the one featuring the Nike basketball. Right now, the text 'The first of its kind' is part of the background im ...

Is it possible to utilize the event load function while offline with a text file?

Is there a way to load a div that I have saved as plain text (in a file)? The file is located in the same root directory as my HTML page. I am attempting to call this file using jQuery's event load on my HTML page like this: $("#tab2").load("textfile ...

"Unraveling the Perpetual Animation D

I am looking to create a simple menu where a div called "test" is initially hidden, and when I click on a div labeled "trig", the test div is shown. If I click on trig again, the test div should hide. However, I am running into an issue where each subseque ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...

PHP and XML encountered a parsing error: unexpected occurrence of the T_OBJECT_OPERATOR

I've been troubleshooting a PHP page that reads data from an XML file. I keep running into this error message: Parse error: parse error, unexpected T_OBJECT_OPERATOR on line 24. I'm unsure of the cause of the error and need help figuring out what ...

Trouble altering an attribute using jquery

Hey there, I'm struggling with changing the attribute for an id and can't quite pinpoint where I'm going wrong. It's not making things easier that I'm pretty new to this whole thing as well. I've created a function to ensure ...

How come the Google fonts won't display correctly within my HTML document?

After importing some fonts into my CSS file, I noticed that they are not displaying correctly in the design. Below is the code for the imported fonts and CSS linking: https://i.stack.imgur.com/9RQ4u.png The output only shows sans-sarif working properly: ...