简体   繁体   中英

Checked Checkbox value in span

I am using a filter for a site and need those checked values to be show in a div in a span. I have gone through the article of Stack Overflow in which it is showing in a div, but I want the value to be show in span tag. Below is the code I am using of Stack Overflow for the values.

jQuery:

$(document).ready(function()
{
    var el = $('.dropdown_box ');
    var text= el.text();
    $('.dropdown_container').on('click', 'li', function()
    {
        var filter = [];
        $.each($('.dropdown_container').find(':checked'), function(i, el)
        {
            filter.push(el.value);
        });
        el.text(text + ('') + filter.join (''));
    });
});

HTML:

<div class="dropdown_box">
    Filter Items :
</div>
<div class="dropdown_container">
    <ul>
        <li><input type="checkbox" name="filter[]" value="Black" class="cbx"/>Black</li>
        <li><input type="checkbox" name="filter[]" value="Red" class="cbx"/>Red</li>
        <li><input type="checkbox" name="filter[]" value="brown" class="cbx"/>brown</li>
        <li><input type="checkbox" name="filter[]" value="pink" class="cbx"/>pink</li>
        <li><input type="checkbox" name="filter[]" value="purple" class="cbx"/>purple</li>
        <li><input type="checkbox" name="filter[]" value="Orange" class="cbx"/>Orange</li>
    </ul>
</div>

Define your filter array outside .on

Example

var filter = [];
$('.dropdown_container').on('click', 'li', function()
{

because every-time you click your filter array variable is re-initialize.

    $(document).ready(function()
    {
        var el = $('.dropdown_box ');
        var text= el.text();
        $('.dropdown_container').on('click', 'li', function()
        {
 var filter = [];

            $.each($('.dropdown_container').find(':checked'), function(i, el)
            {


filter.push("<span>"+el.value +"</span>");

            });

     $('.dropdown_box').html(filter);

        });
    });

Not checked the result try this

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