select and unselect from a dropdown list

648 views Asked by At

In multiselect jquery dropdown, I want if an item checked it gors to an array and if an item is unchecked it removes from that array. I did:

var optionValues = [];
$("#myselect").change(function() {
    $("select option:selected").each(function() {
        optionValues.push($(this).val());
    });

    $('select option:not(:selected)').each(function() {
        itemtoRemove = $(this).val();
        optionValues.splice($.inArray(itemtoRemove, optionValues), 1);
    });
    $('#this').val(optionValues.join());
}).trigger( "change" ); 
<input type="text" id="this">

but it shows nothing in the textbox. Any idea?

3

There are 3 answers

3
Rory McCrossan On BEST ANSWER

It's much easier to use map() to create your array and to also create a brand new array on each change so you don't have to mess around finding a specific element of the array to remove. Try this:

var optionValues = [];
$('#myselect').change(function() {
    optionValues = $('option:selected', this).map(function() {
        return this.value;
    }).get();
    $('#this').val(optionValues.join());
}).trigger('change');

Example fiddle

0
arun On
$("#myselect").change(function() {
var optionValues = [];
$("select option:selected").each(function() {
    optionValues.push($(this).val());
  });

 $('#this').val(optionValues.join());
}).trigger( "change" ); 

http://jsbin.com/gejigucimo/1/edit

0
Rasalom On

The problem is that you not checking for return of $.inArray(itemtoRemove, optionValues) call.

$('select option:not(:selected)').each(function() {
        itemtoRemove = $(this).val();
        var index = $.inArray(itemtoRemove, optionValues);
        if(index != -1) {
            optionValues.splice(index,1);
        }
 });

http://jsfiddle.net/00shke8a/