How to force the "change" event of an input select, even without choosing another value?

1

There are two problems:

1 - When loading an input select I tried to use a trigger to force the change, but it did not work.

2 - I have 2 selects. When I actually change the value of the first one, the change event is called and "hides" values from the other select, however if the value that was hidden is the current selected it does not add to the combo, only from the list.

How to make the initial change work and how do I delete the items I tried to hide correctly?

Follow the code on fiddle to check for errors: link

JS:

$("#cb").trigger("change");
$("#cb").on("change", function(){
    var cb1val = $(this).val();
    $("#cb2 option").each(function(){
        if($(this).val() <= cb1val){
             $(this).hide();   
        }
        else{
            $(this).show();
        }            
    });
});

HTML:

<select id="cb">
    <option value="0">Valor 1</option>
    <option value="1">Valor 2</option>
    <option value="2">Valor 3</option>
    <option value="3">Valor 4</option>
    <option value="4">Valor 5</option>
</select>

<select id="cb2">
    <option value="0">Valor 1</option>
    <option value="1">Valor 2</option>
    <option value="2">Valor 3</option>
    <option value="3">Valor 4</option>
    <option value="4">Valor 5</option>
</select>
    
asked by anonymous 22.05.2014 / 20:22

2 answers

3

Just simulate the change as follows:

$("selector").change();

Change the JS to:

$("#cb").change(function(){
    var cb1val = $(this).val();
    $("#cb2 option").each(function(){
        if($(this).val() <= cb1val){
             $(this).hide();   
        }
        else{
            $(this).show();
        }            
    });
    //Resposta pergunta 2
    $("#cb2 option[value="+cb1val+"]").attr("selected","selected");
});
$("#cb").change();
    
22.05.2014 / 20:29
1

With pure javascript you can use onchange()

document.getElementById("cb").onchange();

The second problem is solved like this:

$(this).show().attr('selected',true); // assim você seleciona o item que pode ser exibido
    
22.05.2014 / 20:32