How to change the value of a select?

2

I have a script that checks the difference between two sets of dates, and I want it when one of these differences is greater than the other, that the previously chosen value of a certain select changes.

As a snippet of code is worth a thousand words:

 if (daysc > daysb) {

    $("#var1").show();
    $("#var2").hide();
    $("#var3").val('mudaestevalor');
}

But it's not working. I have another function after this, which opens a div only if $var3 has a certain value:

if ($('#var3').val() == 'mudaestevalor')
        {
       abre div

        } 

But it is not changing with .val() . I've tried other variants, I've looked at some answers from here and from SOen and nothing. Some variants I tested:

$("select#var3").trigger("mudaestevalor");
$("select#var3 option").val('mudaestevalor').change();
$("select#var3 option").val('mudaestevalor');

Minimum example in fiddle: link

    
asked by anonymous 27.07.2015 / 23:31

1 answer

3

You have to do this in the right order.

1- add the event handler > $('#var3').on('change', function () {
2- change the value of select > $("#var3").val('value2')
3- fire the event change > .change();

$('#var3').on('change', function () {
    if (this.value == 'value2') $("#div1").show();
    else $("#div1").hide();
});

if (2 > 1) {
    $("#var3").val('value2').change();
}

jsFiddle: link

    
28.07.2015 / 00:15