从下拉框中获取复选框的值

Getting value of checkbox from dropdown

本文关键字:复选框 获取      更新时间:2023-09-26

我真的被卡在这里了&我想我错过了一些很明显的东西。请帮助我(我是一个初学者在html,javascript)

我已经做了一个dropdown包含一个无序列表项目,我从JSON填充。这里是填充列表的代码:

    var oldJSON = null;
    setTimeout(function main_func() { 
            var counter=0;
            $.getJSON('mydata.json', function(data) { 
                    if(JSON.stringify(oldJSON) != JSON.stringify(data)){ 
                        //$(".dropdown").html("");
                        //$("#notifications").append("<option style=display:none></option>")
                        $.each(data.items, function(i, v) {
                                counter++;  
                                document.getElementById('test').innerHTML=counter ;
                                $('.dropdown').append('<li><input type="checkbox" value="'+counter+'"id="'+ counter +'"><label for="'+ counter +'"><div id="type">' + v.type +'</div>'+'<div id="text">' +v.text +'</div>'+'<div id="pnr">'+v.pnr+'</div>'+ '</label></li>');
                                ;});
                    }
                    oldJSON = data;
            });
            setTimeout(main_func,2000); 
    });
现在,我的下拉菜单(考虑它是一个facebook类型的通知)包含复选框(对于标记为已读-还没有实现它)。我需要从复选框中获取值。现在我得到的是空白值。有人能告诉我正确的方向吗?这是我的html:
<div id="selected_item"></div>
<section class="main">
    <div class="wrapper-demo">
        <div id="dd" class="wrapper-dropdown-4">
            <ul class="dropdown"></ul>
        </div>
        <div class="main_func"></div>
        <div id="test"></div>
    ​</div> 
</section>

,下面是与它一起使用的javascript(它不起作用):

$('.dropdown input[type="checkbox"]').on('click', function () {
    var title = $(this).closest('.dropdown').find('input[type="checkbox"]').val(),
    title = $(this).val() + ","; 
    if ($(this).is(':checked')) {
        $('.selected_item').append(title);
    } 
});

如果你能更好地表达,请编辑这个问题;)。这里粘贴了html css json

的代码

试试这个演示

$('.dropdown input[type="checkbox"]').on('click', function () {
    var title = "";
    $('.dropdown input[type="checkbox"]').each(function(){           
    if ($(this).is(':checked')) {
        if(title != "")
            title = title + ',';
        title = title + $(this).val();            
    } 
    $('#selected_item').html(title);
    });
});