user1298215
user1298215

Reputation: 41

How to add/remove dropdown multiselect list items in jquery

I am using a multiselect dropdown list and filled items from database like below, it works fine the first time, but based on selections from other dropdowns, I need to remove values and add other values.

$('#PID').multiselect({
    columns: 1,
    placeholder: 'Select project'
});

I am unable to modify the dropdown's values, can anybody help me?

I referred to the link below.

http://www.codexworld.com/multi-select-dropdown-list-with-checkbox-jquery/

I tried something like the following:

$("#PID").append('<option value="option5">Option ' + ++count + '</option>');
$("#PID").multiselect('refresh');

Upvotes: 0

Views: 2226

Answers (2)

Md Nazrul Islam
Md Nazrul Islam

Reputation: 373

Demo link http://www.designchemical.com/blog/index.php/jquery/create-add-remove-select-lists-using-jquery/

<form>
  <fieldset>

    <select name="selectfrom" id="select-from" multiple size="5">
      <option value="1">Item 1</option>
      <option value="2">Item 2</option>
      <option value="3">Item 3</option>
      <option value="4">Item 4</option>
    </select>

    <a href="JavaScript:void(0);" id="btn-add">Add &raquo;</a>
    <a href="JavaScript:void(0);" id="btn-remove">&laquo; Remove</a>

    <select name="selectto" id="select-to" multiple size="5">
      <option value="5">Item 5</option>
      <option value="6">Item 6</option>
      <option value="7">Item 7</option>
    </select>

  </fieldset>
</form>

The JQuery Code

$(document).ready(function() {

    $('#btn-add').click(function(){
        $('#select-from option:selected').each( function() {
                $('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
            $(this).remove();
        });
    });
    $('#btn-remove').click(function(){
        $('#select-to option:selected').each( function() {
            $('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
            $(this).remove();
        });
    });

});

Upvotes: 3

Jayakrishnan
Jayakrishnan

Reputation: 4294

You can unload multiselect dropdown using below code and reinitialize it:

$('#PID').multiselect( 'unload' );

You can also reload using below code:

$('#PID').multiselect( 'reload' );

Please check here for more options.

Upvotes: 0

Related Questions