robloxGamer3029
robloxGamer3029

Reputation: 55

How to get value of <ion-select> no jQuery

I have a user form in which the user gets to choose from three countries and displays it back to the user in the form of an alert. It looks something like this:

function myFunction() {
  //alert back to user
  alert(document.getElementById("options").value)
}
<head>
  <script type="module" src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.esm.js"></script>
  <script nomodule src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ionic/core/css/ionic.bundle.css" />

</head>

<ion-list>
  <ion-item style="display: none;">
    <ion-label style="display: none;">
      Select Region
    </ion-label>
    <ion-select style="display: none;" id="options">
      <ion-select-option>USA</ion-select-option>
      <ion-select-option>UK</ion-select-option>
      <ion-select-option>Canada</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

<button onclick="myFunction()">Click to retrieve</button>

Again, as the title suggests, I do NOT want to use jquery, I only want to use Native, Vanilla JavaScript.

How would I do this?

Upvotes: 0

Views: 356

Answers (2)

terrymorse
terrymorse

Reputation: 7086

Here's your code, having removed the style="display: none", revealing the select.

The code works fine, but the alert shows 'undefined' until you select one of the options.

const opts = document.getElementById("options");

function myFunction() {
  alert('ion-select value: ' + opts.value);
}

// listen for changes to the ion-select
opts.addEventListener('ionChange', function () {
  console.log('ion-select ionChange detected');
});
<head>
  <script type="module" src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.esm.js"></script>
  <script nomodule src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ionic/core/css/ionic.bundle.css" />

</head>

<ion-list>
  <ion-item>
    <ion-label>
      Select Region
    </ion-label>
    <ion-select id="options">
      <ion-select-option>USA</ion-select-option>
      <ion-select-option>UK</ion-select-option>
      <ion-select-option>Canada</ion-select-option>
    </ion-select>
  </ion-item>
</ion-list>

<button onclick="myFunction()">Click to retrieve</button>

Upvotes: 1

Dacxj0
Dacxj0

Reputation: 161

It seems that you’re doing the right thing but, have you tried to set a value to each option?

Like

<ion-select-option value=“USA”>USA</ion-select-option>

Upvotes: 0

Related Questions