In my meteor application, I need to get the current value of a select option field.
My markup:
<select multiple id="category">
<option value="" disabled selected>Please select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
In the template events I declare the event map as follow:
Template.objectsList.events({
// #category represents my select option input
"change #category": function (event) {
console.log(event.target.options);
},
// ...
});
in the console this would always print:
[option, option, option, option, selectedIndex: 0, namedItem: function, add: function, remove: function, item: function]
0: option
1: option
2: option
3: option
length: 4
selectedIndex: 0
__proto__: HTMLOptionsCollection
No matter, which option I select in the browser window, the selectedIndex attribute would always equal 0. How can I get the actual selectedIndex, so I can get the value of the currently selected item?
EDIT 1
I'm using materialize as UI framework and I initiate my select option fields as follow:
$(document).ready(function() {
$('select').material_select();
});
EDIT 2
It has to do with how the select option element is rendered with materialize, there is a similar question on SO and discussion on github about this topic.
Thing is, materialize would manipulate the DOM and render a ul List instead of the initial select option
element:
<input type="text" class="select-dropdown" readonly="true" data-activates="select-options-76ad55d8-1376-b852-a496-ef2926e59632" value="Please select">
<ul id="select-options-76ad55d8-1376-b852-a496-ef2926e59632" class="dropdown-content select-dropdown" style="width: 420px; position: absolute; top: 0px; left: 0px; opacity: 1; display: none;">
<li class="disabled"><span>Please select</span></li>
<li class=""><span>Option 1</span></li>
<li class=""><span>Option 2</span></li>
<li class="active"><span>Option 3</span></li>
</ul>
So the solution would be to either
- A get the selected value from the rendered ul li list (ugly)
- execute the JS init at the time after the onchange event would already have gathered the current values (if possible)