dropdown.js icon indicating copy to clipboard operation
dropdown.js copied to clipboard

How to change which item is selected?

Open Kirkman opened this issue 9 years ago • 12 comments

I am using a dropdown together with a clickable map. If someone clicks an item in the map, I want to update the <select> list to show that item as being selected.

Doing this doesn't seem to work:

$('#map-container .sample select').val("3");

Kirkman avatar Apr 27 '15 19:04 Kirkman

Yes I was wondering if there was a way to programmatically change selected option.

jaspersorrio avatar Jul 01 '15 06:07 jaspersorrio

You can change the selection in the select element and trigger the change event

FezVrasta avatar Jul 01 '15 12:07 FezVrasta

I tried these following but it doesn't work, did I miss something?

    $('.select-dropdown').on('change', function() {
            $(".select-dropdown").dropdown();
    });
    $('.select-dropdown').on('change', function() {
            $(".select-dropdown").dropdown({ "dropdownClass": "select-dropdown"});
    });

adpauly avatar Jul 24 '15 20:07 adpauly

What about

$(".select").val("x").trigger("change");

FezVrasta avatar Jul 24 '15 21:07 FezVrasta

$(".select").val("x").trigger("change"); // Does not work..

$(".select").val(); // gets the value $(".select").val("x").trigger("change"); // does not set it..

Please help asap..

nekkon avatar Aug 03 '15 12:08 nekkon

It was working, looks like some commit removed the feature..

FezVrasta avatar Aug 03 '15 16:08 FezVrasta

Had to fix it by myself, please support your plugin.. I'll be using it at my projects.

Fix:

$select.on("change", function(e) {
          var $this = $(e.target);
          if (!$this.val().length) return;

          if (!multi) {
            var $selected;
            if ($select.find(":selected").length) {
              $selected = $select.find(":selected").last();
            }
            else {
              $selected = $select.find("option, li").first();
              // $selected = $select.find("option").first();
            }
            methods._select($dropdown, $selected);
          } else {
            methods._select($dropdown, $select.find(":selected"));
          }
        });

Add this on line 170 in the .js file and $(".select").val("x").trigger("change"); will work..

nekkon avatar Aug 04 '15 04:08 nekkon

Feel free to send a PR

FezVrasta avatar Aug 04 '15 07:08 FezVrasta

Thanks for the fix nekkon.

Nicks182 avatar Oct 07 '15 06:10 Nicks182

I got the same issue. In my case, I cannot use .trigger("change") because I want 2 selects are both the same value when each one changed. How should I do?

thanh-taro avatar Apr 26 '16 02:04 thanh-taro

Does this fix address when no item is selected?

selectedIndex = -1

Doesn't seem to work.

sgtshellback avatar Jan 27 '17 00:01 sgtshellback

nekkon's fix still works

colinrlly avatar Jun 27 '17 18:06 colinrlly