I am using jquery-select2 library to implement my dropdowns.
In my case, I would like to be able to trigger an action after a user clicks on the option in the dropdown list. However, the click or change event doesn't seem to work
haml file:
%select.medium.name_selector.pull_left
%option.placeholder{value:"placeholder", disabled: "disabled", selected: "selected"} Start or find a conversation with a muser
%option{value: "nick"} nick
%option{value: "sam"} sam
%option{value: "john} john
coffeescript file:
events:
"click option" : "displayChatScreen"
displayChatScreen: (e) ->
e.preventDefault()
nickname = @$("select.name_selector option:selected").val()
if nickname != "placeholder"
Backbone.history.navigate "messages/#{nickname}",
trigger: true
else
alert "You need to select a friend to chat"
Is there anyway to trigger the action once I change the option of my select2 dropdown box?
Note: I have tried both click and change events and they both do not work
With select2 you can't use the normal change
event as you would for a normal <select>
widget, but you actually need to attach your displayChatScreen
method to the change
handler provided by select2.
e.g.
$('select.medium.name_selector').on('change', this.displayChatScreen);
Assuming that's the selector for your select2 widget and you're running that in the appropriate context.
When you use the default events
hash provided by Backbone, you're really doing this:
$el.on('change', 'option', this.displayChatScreen);
Since select2 actually replaces the <select>
(and therefore <option>
tags with a <ul>
<li>
pair) you'll never actually receive the browser event.
Additionally, the change
event fires on the parent <select>
not the <option>
element.
You can avoid the issue all together by not rendering the options and instead passing it as an option to the select2 when initializing.
You can make an input tag like this:
<input name="someName" value="selectedValues">
Then initialize select2 with the options like this:
$('input[name="SomeName"]').select2(options);
Doing this will allow you to safely listen to the changes to the input just as you would regularly do using the events hash.