0

I am doing a small project with Mysql as backend, Flask as framework. When I load the page, drop down list should be populated with values from database (onLoading() in my code.When I select "All" option from drop down list with checkboxes(I can select multiple), all the options in the list should be checked. when I am unchecking "All", all options should be unchecked. I tried this code. But somehow it is not working. console.log is printing "Outside" and "Inside" correctly when I am selecting 'All' but other options are not getting checked. May I know where the flaw is in my code.

HTML

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

    </select>
</body>

Javascript

<script type="text/javascript">

        $('#nodes-select').change(function(){
            console.log("Outside");
            if($("#nodes-select option[value='-1']").is(':selected'))
            {
                console.log("Inside");
                $('#nodes-select option').prop('selected', true);
                $("#nodes-select option[value='-1']").prop('selected', false);
            }

        });


        function onLoading()
        {
            alert("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: tmp[i],
                    text : tmp[i]
                    }));
                }
                $('#nodes-select').multiselect('rebuild');


            });        


        }

</script>
krish
  • 167
  • 1
  • 3
  • 12

1 Answers1

2

That is because you are using the multi-select plugin.

The actual select is being replaced by the pretty one. (and they do not share a two-way binding of properties).

So you need to call the refresh method after making changes to the select element.

$('#nodes-select').change(function() {
  console.log("Outside");
  if ($("#nodes-select option[value='-1']").is(':selected')) {
    console.log("Inside");
    $('#nodes-select option').prop('selected', true);
    $("#nodes-select option[value='-1']").prop('selected', false);
  }
  // add the following line to refresh the multiselect element.
  $('#nodes-select').multiselect('refresh');
});
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317