How to change the value of a select?

Asked

Viewed 1,437 times

2

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

How an excerpt 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 have a certain value:

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

        } 

But she’s not changing with .val(). I tried other variants, looked at some answers from here and of 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: http://jsfiddle.net/gustavox/axwxbyx6/2/

  • 1

    Their <option> have the attribute value? $("#var3").val('mudaestevalor'); is the right way

  • 1

    Can you put HTML too? if you do a jsFiddle it will be solved in a few minutes :)

  • Yes you have @bfavaretto... Thanks, I’ll make a fiddle...

  • Yes @Sergio will do it right now! :)

  • 1

    select must have an option with value="mudaestevalor".

  • 1

    I did some tests here and in fact it didn’t work '-' if anyone wants to test, I need to leave: https://jsfiddle.net/fyoxwzso/

  • @Kaduamaral joined Event Handler after changing select :P so it wouldn’t work ... -> https://jsfiddle.net/fyoxwzso/1/

  • I don’t know if it’s enough, but I put only one condition 2 > 1 to test (instead of dates), and if you notice, it even puts the value already in select, but it doesn’t open div...) http://jsfiddle.net/gustavox/axwxbyx6/2/ @bfavaretto

  • 2

    haeuhuahueuae didn’t even call me @Sergio was hungry wanting to come away eating kk

Show 4 more comments

1 answer

3


You have to do it in the right order.

1- add Event Handler   > $('#var3').on('change', function () {
2- change the value of select      > $("#var3").val('value2')
3- trigger 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: http://jsfiddle.net/88ssr62g/

  • That’s right... when I go into production I’m gonna put all the scripts in one window.load and then minificar... even so would need to be in the right order? Ah, and thanks again! Hugs!

  • 1

    @gustavox the window.load serves if the change is generated by the user. Programmatically it can be an error. As long as you ensure that the .change() comes after Event Handler in the lapse of the script, all right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.