<select> value turns null after updating it using jQuery

1.1k views Asked by At

So i have this strange problem:

i have a select element with class "Menu_DDL".

i turn it into a jQuery UI .selectmenu() the following way:

$(".Menu_DDL").selectmenu({
    width: "100%",
    change: function (event, ui) {
        event.preventDefault();
    }
});

now i need to update the value programatically, but the select's value does not change:

var temp_email = $(this).attr("MID");
    console.log(temp_email);
    console.log("was: " + edit_email_template_dialog.find(".Menu_DDL").val());
edit_email_template_dialog.find(".Menu_DDL").val(temp_email);
    console.log("now: " + edit_email_template_dialog.find(".Menu_DDL").val());
edit_email_template_dialog.find(".Menu_DDL").selectmenu("refresh", true);
    console.log("refreshed");
edit_email_template_dialog.attr("TID", $(this).parents(".TR_Record").attr("TID"));
edit_email_template_dialog.dialog("open");

the logs from above return the following:

"49" 
"was: 23" 
"now: null" 
"refreshed"

as you can see, the value turns into null after i try to update it. the weird part is, that if run the same code via console eg edit_email_template_dialog.find(".Menu_DDL").val("49"); it works fine.

what am i missing?

1

There are 1 answers

0
Mike Willis On BEST ANSWER

Sometimes I have to set the value of a select menu, and all I know is that the appropriate option might have the value I'm looking for in the value attribute, or in .text(). So I loop through each each option, checking the value attribute AND .text() for example:

// assuming var myValue is the value we're looking for
$(".menu option").each(function(){
    if ( $(this).val() == myValue || $(this).text() == myValue ) {
        $(".menu").val( $(this).val() );
    }
});

You can also make everything lowercase, remove spaces, etc, and print debugging notes:

// assuming var myValue is the value we're looking for
myValue = myValue.toLowerCase().replace( / /g, "" );
var currentValue;
var currentText;
$(".menu option").each(function(){
    currentValue = $(this).val().toLowerCase().replace( / /g, "" );
    currentText = $(this).text().toLowerCase().replace( / /g, "" );
    console.log("checking if '" + currentValue + "' == '" + myValue + "' OR if '" + currentText + "' == '" + myValue + "'");
    if ( currentValue == myValue || currentText == myValue ) {
        console.log(" ... match found, setting value");
        $(".menu").val( $(this).val() );
    }
});

The debugging notes have helped me too. Every once in a while I find a situation where I thought it wasn't finding a match, but it turns out it was (the " ... match found" notice was printed). That helped me figure out that some code later in the same script was resetting the value of the menu.