Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of selected item on change using jQueryUI Selectenu

I am using the Select Menu widget to display a list of states within a form:

<select name="state" id="state">
   <option value = "">Select State</option>
   <option value = "Alabama">Alabama</option>
   <option value= "Alaska">Alaska</option>
   <option value= "Arizona">Arizona</option>
   <option value= "California">California</option>
   <option value= "Colorado">Colorado</option>
   <option value= "Connecticut">Connecticut</option>
 </select>

In my script I have

 $( "#state" ).selectmenu();

Now, what I am trying to do is send out an alert of the value of the selected option. So I have this:

$('select').on('change', function (e) {
    var optionSelected = $("option:selected", this);
    var valueSelected = this.value;
    alert(valueSelected);
});   

The issue is that for some reason none of that is working when I use the JQueryUI function selectmenu()

When I remove that one line, everything functions as normal. It was my understanding that I need to include $( "#state" ).selectmenu(); in order to utilize the JQuery UI theme and functionality.

Can anyone enlighten me on what the issue may be. Again, it works fine if I remove that selectmenu line.

Thanks!

like image 357
user3785198 Avatar asked Nov 02 '14 05:11

user3785198


1 Answers

jQuery UI hides your original <select> and creates custom widjets using dynamically injected elements. So you are no longer clicking on the original <option>'s you provided, and no change event will be triggered on it.

Instead, it emits a selectmenuchange event when the selected item is changed . You can listen to it by passing the handler function to the change option while initializing the plugin.

The item property of second argument passed to the callback function refers to the item you've selected. You can access it's value as shown below:

$("#state").selectmenu({
  change: function(event, ui) {
    alert(ui.item.value);
  }
});
<link href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<select name="state" id="state">
  <option value="">Select State</option>
  <option value="Alabama">Alabama</option>
  <option value="Alaska">Alaska</option>
  <option value="Arizona">Arizona</option>
  <option value="California">California</option>
  <option value="Colorado">Colorado</option>
  <option value="Connecticut">Connecticut</option>
</select>

You can also manually listen to this event like:

$('select').on('selectmenuchange', function (e,ui) {
   alert(ui.item.value);
}); 
like image 107
T J Avatar answered Nov 06 '22 05:11

T J