John S
John S

Reputation: 8349

Adding/removing option from multiselect with jquery

I have jquery that will add an item to a select list and change the background color to indicate that it has been added (the select list is not visible). When I click the plus it adds the item to the list and changes the background to green. When I click it a second time it removes the item and color. This works once. If I repeat the cycle it stops working. Any ideas why that might be?

<ul>
<li><span id='add'> + </span>this is a test
 </li>
</ul>
<select multiple="multiple" id="destination"></select>

$(document).ready(function () {
  $("#add").click(function () {
var color = $("#add").css("background-color");
if (color == "transparent") {
  $("#add").css("background-color", "green");
  $("#destination").append('<option value="1">New option</option>');
} else {
  $("#add").css("background-color", "transparent");
  $("#destination option[value='1']").remove();
}
});
});

Upvotes: 2

Views: 13925

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206699

Don't check for backgrounds, use just the .toggle() event:

http://jsbin.com/unojap/4/edit

  $("#add").toggle(function () {

        $("#add").css("background-color", "green");
        $("#destination").append('<option value="1">New option</option>');

  },function(){
        $("#add").css("background-color", "transparent");
        $("#destination option[value='1']").remove();

  });

Upvotes: 3

Salman Arshad
Salman Arshad

Reputation: 272446

Instead of checking for background colors, use jQuery.data to store whether an element has been added or not:

var added = $(this).data("added");
// returns undefined if requested data does not exist
if (!added) {
    $(this).data("added", true);
    // change background, do stuff
}
else {
    $(this).removeData("added");
    // change background, do stuff
}

Demo

Upvotes: 1

Owen Allen
Owen Allen

Reputation: 11978

This depends on the browser. In example in Chrome $("#add").css("background-color") returns rgba(0,0,0,0) not transparent. Thus reading a background color like this isn't cross-browser compliant.

In general I think you may be better off with classes.

http://jsfiddle.net/watRq/

$(document).ready(function () {
  $("#add").click(function () {
    if ($(this).hasClass("transparent")) {
      $(this).addClass("green").removeClass("transparent");
      $("#destination").append('<option value="1">New option</option>');
   } else {
      $("#add").addClass("transparent").removeClass("green");
      $("#destination option[value='1']").remove();
   }
  });
});

Upvotes: 3

Related Questions