Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery adding and removing items from listbox

I've created this fiddle, it allows the user to click on either art or video, dynamically populating the the second listbox with the list associated with those selections. There are two buttons, one to add the selection to the box, the other which removes the selection.

What I would like to do is prevent the user from adding some that has already been added. The value of the options will all be Guids. Bonus points if you can modify the fiddle to use Guid instead of ints.

I've tried this:

$.each($("#SelectBox2 option:selected"), function (i, ob) {
    if (i == $(this).val()) {

    } else {
        inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
    }
});

I would like to enable the user to remove the selected items from the list.

Thanks,

UPDATE Just letting you guys know what the solution is that I came up with, I got the bonus points because i added GUID to it in a really smart way :) fiddle, I also tidied up the html to make it look nice and neat.

MAJOR UPDATE A massive thanks to everyone who has contributed to this question, I have taken on board everyones comments and fiddles and have generated this >> fiddle <<

like image 678
Callum Linington Avatar asked Mar 21 '13 13:03

Callum Linington


1 Answers

I think you would want to do something like this: Check if value is in select list with JQuery.

Modifying your code to something like this should work:

$("#SelectBox2 option:selected").each(function () {
    var optionVal = $(this).val();
    var exists = false;
    $('#SelectedItems option').each(function(){
        if (this.value == optionVal) {
            exists = true;
        }
    });

    if(!exists) {
        inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
    }
});

Removing selected items would look like this:

$('#remove').click(function () {
    $("#SelectedItems option:selected").remove();
});
like image 51
OptimizedQuery Avatar answered Oct 18 '22 16:10

OptimizedQuery