Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery selectmenu set selected index on change

Tags:

jquery

I am trying to set the selected index of a select box / selectMenu on change back to the first option.

Here is my code so far

    $obj = $("<select class='class1' />");
    $obj.append("<option value='-1' selected='selected' class='icon1'>default</option>");
    $obj.append("<option value='0' class='icon2'>opt1</option>");
    $obj.append("<option value='1' class='icon2'>opt2</option>");
    $obj.append("<option value='2' class='icon2'>opt3</option>");

    $("#container").append($obj);
    $obj.selectmenu({
        transferClasses: true,
        icons: [
            {find: '.icon1', icon: 'ui-icon-flag'},
            {find: '.icon2', icon: 'ui-icon-plus'}
        ],
        change: function(){
            // doesn't work $(this).find("option:first").attr("selected","selected");
            // doesn't work $(this).selectedIndex = 0;
            // doesn't work $(this).val(-1);
            // doesn't work $(this).val("-1");
            // doesn't work $(this).val("");
        }
    });

Look at this Fiddle, The top dropdown menu I have altered. If you change the value, and re-open the dropdown menu the selected value 'jumps' to the one i changed it to. I want it to be there once i select any value.

like image 446
rlemon Avatar asked Feb 23 '23 05:02

rlemon


1 Answers

This seems to work for me:

$("select").change(function(){
    $('select :first-child').attr('selected','selected');
});

http://jsfiddle.net/CzRWD/

or if you'd rather use $(this) you can do:

$("select").change(function(){
    $(this).children(":first").attr('selected','selected');
});

http://jsfiddle.net/CzRWD/1/

UPDATE

After a bit of playing around and quite a lot of research, I discovered that the way to change the index in the selectmenu plugin is to use the value property and pass in the value of the item you want to select.

This is done inside the change event:

$(this).selectmenu("value",$(this).children(":first").val());

Here's a working example using your jsfiddle: http://jsfiddle.net/GXtpC/86/

like image 85
Jamie Dixon Avatar answered Mar 04 '23 22:03

Jamie Dixon