Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I remove a choice from a select list with jQuery?

I have the following:

<select name="CityID" id="CityID">
  <option value="99">Select City</option>
  <option value="01H">AAA</option>
   <option value="01I">BBB</option>
</select>

As soon as the clicks on the select to choose an option I would like to remove the first line with option value="99".

Can I do this with jQuery? I think I can do it with the .changed() event but are there other events that will pick up the user clicking on the select before the .changed()?

Upvotes: 1

Views: 198

Answers (2)

rkw
rkw

Reputation: 7297

Bryan's answer is the correct one; but here is an alternative that may not be compatible with every browser:

<select name="CityID" id="CityID" required>
  <option value="" disabled selected >Select City</option>
  <option value="01H">AAA</option>
   <option value="01I">BBB</option>
</select>

http://jsfiddle.net/ApeHg/2/

The required on the select element is html5, but it forces the user to select an element before they can submit the form (you can also re-create this behavior for older browsers)

The disabled selected properties on the first element tries to simulate the behavior you looking for, an un-selectable default.

Upvotes: 1

Bryan
Bryan

Reputation: 6752

$('select[name="CityID"]').focus(function() {
    $('option[value="99"]:first', this).remove();
});

Upvotes: 4

Related Questions