Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  25] [ 5]  / answers: 1 / hits: 46724  / 11 Years ago, thu, march 21, 2013, 12:00:00

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 <<


More From » jquery

 Answers
35

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();
});

[#79439] Wednesday, March 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabinal

Total Points: 144
Total Questions: 112
Total Answers: 107

Location: Ghana
Member since Mon, Aug 22, 2022
2 Years ago
;