Fabrizio
Fabrizio

Reputation: 3776

SELECTS: Hide the selected option on a secondary select

I have two select with the same elements (options) in it. What I am trying to do is that when the user select a value from the first select box, the second select box hides that option, and automatically select the first visible option if the selected option was the same as the one in the first select.

I know that :first selects the first element of a group of "objects", and that :visible only select the "visible" ones, so i was thinking that using :first of :visible should work, but what I am getting is no selection at all.

if I remove the :visible it works unless the second select box has the first element selected, and the user selects the first element on the first select box

This is what I have so far, please keep in mind that I have tried :first and :visible in any combination, but I really think that the problem here is that "hide hasn't finished its job when I use :visible

$('#style_position').change(function(){
    var sel_pos_id      = $(this).val();
    var sel_xtr_pos_id  = $('#style_position_extra').val();
    $('#style_position_extra option[value=' + sel_pos_id + ']').hide().siblings().show();
    if(sel_pos_id==sel_xtr_pos_id){
        $('#style_position_extra option')
            .removeAttr('selected')
            .filter(':visible')   //I also tried find(':visible')
            .filter(':first')     //I also tried find(':first')
                .attr('selected','selected');
    }
});

Upvotes: 1

Views: 169

Answers (2)

Fabrizio
Fabrizio

Reputation: 3776

Thanks to charlietfl I figured out, here is the final answer:

$('#style_position').change(function(){
    var sel_pos_id      = $(this).val();
    var sel_xtr_pos_id  = $('#style_position_extra').val();

    var selected=$(this).find('option').not(':selected').clone();
    $('#style_position_extra').html(selected)
    if(sel_pos_id!=sel_xtr_pos_id){
        $('#style_position_extra option[value=' + sel_xtr_pos_id + ']').attr('selected','selected');
    }
});

This code will automatically select a different option if the two selects have the same option, or it will keep the same option selected in the second selectbox

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Here's one method

/* cache a set of options from second select*/
var $opts=$('#style_position_extra option').clone();

$('#style_position').change(function(){
    var sel_pos_id      = $(this).val();
    /* find matching option copy*/
    var $newOpts=$opts.filter(function(){
            return this.value !=sel_pos_id;                                             
    }).clone();
    /* replace exisiting options with match*/
    $('#style_position_extra').html( $newOpts);
});

Here's another possibly simpler one

$('#style_position').change(function(){
    var selected=$(this).find('option').not(':selected').clone();
    $('#style_position_extra').html(selected);
});

Upvotes: 1

Related Questions