34

first post here, I come in peace :) I've searched but can't quite find what I'm after.

I am trying to manipulate the selected option of a select box. Can someone please explain why this works:

$('#some_select_box').click(function() {
  $('#some_select_box option:selected').remove();
});

but this doesn't:

$('#some_select_box').click(function() {
  $('this option:selected').remove();
});

I just want to use "this" instead of spelling out the id of the select box - can someone point me in the right direction for the correct syntax? It's driving me mad because it looks like it should be really simple. And I'm sure it is to someone, but not me, cos its the end of the day and I'm brain-fried... Any pointers much appreciated.

Cheers

Artemis
  • 2,553
  • 7
  • 21
  • 36
odavy
  • 485
  • 1
  • 4
  • 10

6 Answers6

62

this isn't a css selector. you can avoid spelling the id of this by passing it as a context:

$('option:selected', this).remove();

http://api.jquery.com/jQuery/

Mathieu
  • 5,495
  • 2
  • 31
  • 48
  • That's great, thanks... Looks like there's much more jquery left to learn. Wasn't aware of that syntax. Many thanks :) – odavy Mar 23 '10 at 11:17
12
 $('#some_select_box').click(function() {
     $(this).find('option:selected').remove();
 });

Using the find method.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
4

This is a simpler one

$('#some_select_box').find('option:selected').remove();
raveren
  • 17,799
  • 12
  • 70
  • 83
Siddartha
  • 49
  • 1
  • 1
4

This should do the trick:

$('#some_select_box').click(function() {
  $('option:selected', this ).remove();
});
MicE
  • 5,038
  • 2
  • 29
  • 26
0

$('#some_select_box option:selected').remove();

Andres Zambrano
  • 23
  • 1
  • 10
0

The above option works in create form, but the most accurate method is to remove only the disabled value, why?

think about it, when you want to use it in the edit form you need to remove only the disabled selected option otherwise it will remove all selected options from the multi-select dropdown.

remove disbaled value from dropdown

$('#some_select_box').find('option:disabled').remove().end();

above will remove option like below

<select id="some_select_box" multiple>
   <option disabled selected>Choose Option</option>
</select>
Hadayat Niazi
  • 1,991
  • 3
  • 16
  • 28