Topic: SELECT set value from JS

szaiftamas priority asked 3 years ago


I would like to change the SELECT selected option from JavaScript. If I add class="select" this doesn't work. I also tried it through "value" and "selectedIndex".

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>Material Design for Bootstrap</title>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" />
    <!-- Google Fonts Roboto -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" />
    <!-- MDB -->
    <link rel="stylesheet" href="../mdb5/css/mdb.min.css" />
  </head>
  <body>
    <div class="mt-1">
      <select id="isactive" name="setup_modal_content" class="select" data-mdb-filter="true">
        <option value="" hidden></option>
        <option value="1">Yes</option>
        <option value="0">No</option>
      </select>
      <label class="form-label select-label">Active</label>
    </div>
    <!-- MDB -->
    <script type="text/javascript" src="../mdb5/js/mdb.min.js"></script>
    <script>
      setTimeout(() => {
        let element = document.getElementById("isactive");
        element.selectedIndex = 1;
        element.value = "0";
        console.log("called");
      }, 1000);
    </script>
  </body>
</html>

Michał Duszak staff answered 3 years ago


Use setValue() method. Here's the solution.

HTML:

      <select id="isactive" name="setup_modal_content" class="select" data-mdb-filter="true">
        <option value="" hidden></option>
        <option value="1">Yes</option>
        <option value="0">No</option>
      </select>
      <label class="form-label select-label">Active</label>

JS:

const instanceEl = document.querySelector('#isactive');
const instance = mdb.Select.getInstance(instanceEl);
instance.setValue('1')

Snippet: https://mdbootstrap.com/snippets/standard/m-duszak/3294576#js-tab-view



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Resolved

Specification of the issue

  • ForumUser: Priority
  • Premium support: Yes
  • Technology: MDB Standard
  • MDB Version: MDB5 3.9.0
  • Device: N/A
  • Browser: Firefox
  • OS: Ubuntu 20.04
  • Provided sample code: No
  • Provided link: No