jQueryui Selectmenu - save value

325 Views Asked by At

:) I dont get how I can save the selected selectmenu-option into a variable? Here is my Selectmenu:

<script>
    $(function() {
        $("#map").selectmenu();
    });
</script>
<form action="#">
    <fieldset>
        <select name="map" id="map">
            <option value="London">London</option>
            <option value="Berlin">Berlin</option>
            <option value="Nevada">Nevada</option>
        </select>
    </fieldset>
</form>

I know that I need an Event. This Event would be select I guess. The jQueryui API Documentation (http://api.jqueryui.com/selectmenu/#event-select) gives the following Code example:

$( ".selector" ).selectmenu({
  select: function( event, ui ) {}
});

But ... what is the .selector in my case? #map?

So it would be

$( "#map" ).selectmenu({
  select: function( event, ui ) {}
});

I guess? But where to insert my "action"? The var map = X;? And how does my code know which of the maps is selected?

Thank you in advance :)

1

There are 1 best solutions below

3
On BEST ANSWER

In the configuration object that you pass to selectmenu(), there is a select property (a.k.a. key). Its value is an anonymous function (a callback). When you click one of the options, the corresponding event raises invoking that function.

You can get the select option with $(this).val();.

$(this) is a jQuery object. In the context of the callback, it is the element which invokes the function. In JavaScript, the this keyword is a very important and complex topic. You can read about it in MDN and here in SO. Basically, in your case, $(this) is the option element that was selected, triggering the click event.

val() is a method of the jQuery object that returns the current value of that object.

Once you have the value, just assign it to your map variable.

var map = "";

$("#map").selectmenu({
  select: function(event, ui) {
    map = $(this).val();
    console.log(map);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<form action="#">
  <fieldset>
    <select name="map" id="map">
      <option value="London">London</option>
      <option value="Berlin">Berlin</option>
      <option value="Nevada">Nevada</option>
    </select>
  </fieldset>
</form>