Bydigi
Bydigi

Reputation: 1

Fetching Data into from an API and assigning to Tom Select options

I have created a form and I am trying to add fetched data from an API to the options field.

Below is my web site link. I have put two different examples below each other. You can scroll down the page and be able to see what I mean.

I used this example code but it did not work.

new TomSelect("#makeField", {
sortField: {
field: "text",
direction: "desc",
},
});

https://pyro.design/

php code

<?php
/**
 * Template Name: Custom Page Template
 *
 * This is the template file for generic pages.
 * You can customize this file to fit your specific needs.
 *
 * @package Pyro
 */
get_header(); ?>
<?php get_template_part("template-parts/navigation"); ?>
<section class="pageDefault">
<form id="form__lead">

<label for="yearField">Select Year:</label>
  <select id="yearField" name="yearField" class="vehicleYear">
  <option value="">Select year</option>
    <option value="2024">2024</option>
    <option value="2023">2023</option>
    <option value="2022">2022</option>
    <option value="2021">2021</option>
    <option value="1958">1958</option>
  </select><br/>

<label for="makeField">Select Make:</label>
  <select id="makeField" name="makeField" class="vehicleMake">
    <!-- Options go here -->
    <option value="">Select make</option>
  </select>
  
</form>
</section>

<?php get_footer(); ?>

JavaScript code

import axios from "axios";
import TomSelect from "tom-select";
const yearField = document.getElementById("yearField");
const makeField = document.getElementById("makeField");
const modelField = document.getElementById("modelField");
let selectedYear = "";
new TomSelect("#yearField", {
  sortField: {
    field: "text",
    direction: "desc",
  },
});
// Event listener to update selectedYear when the year select field changes
yearField.addEventListener("change", function () {
  selectedYear = yearField.value;
  fetchData(); // Fetch data when the year is changed
});
function fetchData() {
  const apiEndpoint = `https://done.ship.cars/makes/?year=${selectedYear}`;
  axios
    .get(apiEndpoint)
    .then(function (response) {
      const data = response.data; // Assuming the response is an array of options
      populateDropdown(data, makeField);
      console.log(data);
    })
    .catch(function (error) {
      console.error("Error fetching data:", error);
      console.log("Response status:", error.response.status);
      console.log("Response data:", error.response.data);
    });
}
function populateDropdown(data, dropdown) {
  dropdown.innerHTML = "";
  const defaultOption = document.createElement("option");
  defaultOption.value = "";
  defaultOption.textContent = "Select make";
  dropdown.appendChild(defaultOption);
  data.forEach(function (item) {
    const option = document.createElement("option");
    option.value = item.make;
    option.textContent = item.make;
    dropdown.appendChild(option);
  });
}

I am trying to load the data being fetched into the options field generated by Tom select js library. I am able to fetch the data but unable to assign it to the options fields dynamically.

Upvotes: 0

Views: 965

Answers (1)

volkerschulz
volkerschulz

Reputation: 2152

When initializing the TomSelect get a handle:

var make_select = new TomSelect("#makeField", {
    sortField: {
        field: "text",
        direction: "desc",
    },
});

Then after your AJAX call has been successfully executed (e.g. inside your populateDropdown function) clear all the previously set data first:

make_select.clearOptions();

and then inside the forEach add one option after the other using:

make_select.addOption({
    id: 4,
    title: 'Something New',
    url: 'http://google.com'
});

Documentation

Upvotes: 2

Related Questions