3

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?

Yuki
  • 3,857
  • 5
  • 25
  • 43
Ved Tiwari
  • 310
  • 4
  • 12

1 Answers1

1

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>
Addis
  • 2,480
  • 2
  • 13
  • 21
  • Thank's for the suggestion, but every time I try to execute this code, the console gives two errors: 'Uncaught TypeError: Cannot read property 'options' of null' and 'Uncaught ReferenceError: editSelects is not defined'. What do these errors mean, and how can I stop this from happening? – Ved Tiwari Dec 29 '19 at 23:15
  • 1
    @VedTiwari, I have updated the answer, check it out. – Addis Dec 30 '19 at 05:28
  • Quick side note: I got no error messages, but the alert keeps saying: "material" sorry I wasn't able to address the problem earlier as I was not around my computer at the time. – Ved Tiwari Jan 02 '20 at 23:38
  • 1
    That's because the value for all options is the same = `material`. Change values to the corresponding months as I did on my answer. If you still have error message, please let me know the message. – Addis Jan 03 '20 at 13:49