Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an option from a select and adding it to another

Tags:

jquery

Okay, so I've had this code that used to work just fine. I recently upgraded my jQuery from 1.4.4 to 1.5.2, and apparently this has quit working. However, I've tried the code with 1.4.4. and 1.3.2 and it won't work there, either.

This did work. I can't figure out why it isn't. Any help?

Edit: start and end are arguments, with the text of the select element's ID.


var selectedIndex = document.getElementById(start).selectedIndex; // get the selected index from the correct select box

if (selectedIndex != -1) {      // if something is selected, do the following:
       var selectedElement = document.getElementById(start).options[selectedIndex]; // get the element that's selected

       if (selectedIndex == (document.getElementById(start).options.length - 1) && selectedIndex != 0) {
           selectedIndex--; // if we're at the bottom of the list, set our selectedIndex variable to the one right before it
       }

       $("#" + start).remove(selectedElement);  // remove the selected element from the start side          
       $("#" + end).append(selectedElement);        // and add it to the end of the ending side
}

Here's an example of an option I want to move.
<option sortable="yes" datatype="string" value="foo" type="arbitrary">Foo</option>

The issue I'm getting is apparently within jQuery itself - using the full version,
expr.replace is not a function [Break On This Error] expr = expr.replace( /\=\s*([^'"]])\s]/g, "='$1']" ); [jquery-latest.debug.js, line 4540]
The error happens when I hit the $.remove portion of the code.

Thanks.

like image 944
tjsimmons Avatar asked May 02 '11 15:05

tjsimmons


2 Answers

You are getting this error because .remove() takes a string selector, and if none is supplied, removes those of the parent object. Try

$(selectedElement).remove();
like image 80
mattsven Avatar answered Sep 30 '22 18:09

mattsven


Is there a reason you're using the getElementById calls? Let jQuery do the work for you... Instead of using:

$("#" + start).remove(selectedElement);  // remove the selected element from the start side          
$("#" + end).append(selectedElement);        // and add it to the end of the ending side

}

try using:

$("#"+start+" option:selected").appendTo("#" + end);

It combines the remove/append operations into one, and may solve your problem.

like image 43
Ben Avatar answered Sep 30 '22 17:09

Ben