JQuery在下拉框中选择所有值,复选框不起作用

JQuery select all values in a dropdown with checkbox not working

本文关键字:复选框 不起作用 选择 JQuery      更新时间:2023-09-26

我使用Flask作为我的应用程序的框架。我有两个下拉复选框,其中有id"节点选择",它将与从数据库中获取的值填充。第二个列表具有静态名称。在页面加载时,我必须选择两个列表中的所有复选框。第一个下拉菜单(节点选择)工作正常。但是第二个下拉框没有选择任何复选框。我试过这个代码。纠正我错在哪里?

<body onload = onLoading()>
    <select id="nodes-select" multiple="multiple">
    </select>
    <select id="filter-select" multiple="multiple" >
    </select>
</body>
Javascript

<script type="text/javascript">
$('#nodes-select').change(function(){
    console.log("Atleast nodes...");
    if($("#nodes-select option[value='-1']").is(':selected'))
    {
        console.log("node...");
        $('#nodes-select option').prop('selected', true);
        $("#nodes-select option[value='-1']").prop('selected', false);
    }
    $('#nodes-select').multiselect('refresh');
});
$('#filter-select').change(function(){
    console.log("Atleast filter...");
    if($("#filter-select option[value='-1']").is(':selected'))
    {
        console.log("filter ...");
        $('#filter-select option').prop('selected', true);
        $("#filter-select option[value='-1']").prop('selected', false);
    }
    $('#filter-select').multiselect('refresh');
});
function onLoading()
{
    alert("Page Loaded");
    $.get("/nodes",function(data,status)
          {
        var tmp = data.output; 
        console.log("**"+tmp);
        $('#nodes-select').append($('<option>', {
            value: -1,
            text : "All"
        }));  
        for(var i =0;i<tmp.length;i++)
        {
            console.log(tmp[i]);
            $('#nodes-select').append($('<option>', {
                value: i,
                text : tmp[i]
            }));
        }
        $('#nodes-select').multiselect('rebuild');
        $('#nodes-select option').prop('selected', true);
        $("#nodes-select option[value='-1']").prop('selected', false);
        $('#nodes-select').multiselect('refresh');
        $('#filter-select').append($('<option>', {
            value: -1,
            text : "All"
        })); 
        console.log("&&") ;                       
        var temp = ["MAC","SUBLBL","VRF","IFHNDL","COMP_ID","V4_ADDR","V6_ADDR"];
        for(var i =0;i<temp.length;i++)
        {
            console.log(temp[i]);
            $('#filter-select').append($('<option>', {
                value: i,
                text : temp[i]
            }));
        }
        $('#filter-select').multiselect('rebuild');
        $('#filter-select').prop('selected', true);
        $("#filter-select option[value='-1']").prop('selected', false);
        $('#filter-select').multiselect('refresh');
    });
}            
</script>

看起来您忘记查询#filter-select的实际选项了

改变这一行:

$('#filter-select').prop('selected', true);

:

$('#filter-select option').prop('selected', true);