javascripthtmlonsen-ui

How do I save the value of "ons-select" into a variable for JavaScript?


I'm trying to make a code in Onsen Ui whichsaves the date in a variable, and displays the value selected as an alert in JavaScript. Here's a snippet of my code so far:

function exfunction() {
  var MONTH = document.getElementById("Month");
  alert(selectedItem);
}
<ons-select id="Month" onchange="editSelects()" v-model="selectedItem">
    <option value="material">January</option>
    <option value="material">Febuary</option>
    <option value="material">March</option>
    <option value="material">April</option>
    <option value="material">May</option>
    <option value="material">June</option>
    <option value="material">July</option>
    <option value="material">August</option>
    <option value="material">September</option>
    <option value="material">October</option>
    <option value="material">November</option>
    <option value="material">December</option>
</ons-select>

So I need help on storing the value of the selected item in the ONS-SELECT in a variable to use in JavaScript. Any suggestions?


Solution

  • Use options property on the ons-select element to get a node list of all the options, and then use selectedIndex property to get the index of the currently selected option.

    function editSelects() {
      const selectTag = document.getElementById("Month");
      const months = selectTag.options;
      var selectedMonth = months[selectTag.selectedIndex].value;
      alert( selectedMonth )
    }
    
    <ons-select id="Month" onchange="editSelects()" v-model="selectedItem">
        <option value="January">January</option>
        <option value="Febuary">Febuary</option>
        <option value="March">March</option>
        <option value="April">April</option>
        <option value="May">May</option>
        <option value="June">June</option>
        <option value="July">July</option>
        <option value="August">August</option>
        <option value="September">September</option>
        <option value="October">October</option>
        <option value="November">November</option>
        <option value="December">December</option>
    </ons-select>