Brian J Brian J - 4 months ago 12
jQuery Question

Remove default option onChange event of selected select element?

I have two HTML select elements on a form. In the current setup the default option for both selects is read in from the database.

When the selected item changes in a select I want to remove the default option from that select element not others.

The issue at the moment is that, when I change the selected item in one Select, the default option is removed from both Selects. Where it should only be removed from the control that fires the change event.

I did try also using

$('option:selected', this).remove();
on each independent change event. But this code removes an item from the select on every change. Where as the use case requires only removing the default option.

How can you remove the default option of only the selected select element?

So in the markup I defined two select elements with ID's
EventName
and
Status
:

<!-- SELECT STATUS STATIC-->
<div class="form-group">
<label class="col-md-9 control-label" style="text-align: left;" for="Current Status">Current Status</label>
<div class="col-md-4">
<select id="Status" name="Status" style="width:165px;" class="btn btn-default">
@foreach (Models.RecStatus status in Model.Status)
{
<option value="@status.RecStatus">@status.RecStatus</option>
}
</select>
</div>
</div>


<!-- SELECT EVENT STATIC-->
<div class="form-group">
<label class="col-md-9 control-label" style="text-align: left;" for="Event">Event</label>
<div class="col-md-4">
<select id="EventName" name="EventName" style="width:165px;" class="btn btn-default">
@foreach (Models.RecEvent eventType in Model.Event)
{
<option value="@eventType.EventType">@eventType.EventType</option>
}
</select>
</div>
</div>


//Remove the extra default Event and Status select elements
//onChange
$('#EventName').on('change', function() {
//$('option:selected', this).remove();
$("#defaultOption").remove();
});



$('#Status').on('change', function() {
//$('option:selected', this).remove();
$("#defaultOption").remove();
});

Answer

you could remove them based on their value

$('#EventName').one('change', function() {
    $(this).find("option[value='']").remove();
}

or you could remove the last option

$('#EventName').one('change', function() {
    $(this).find('option:last').remove();
}
Comments