Home > Software engineering >  How to manipulate values from dropdown and pass it when clicked as a parameter to api in other funct
How to manipulate values from dropdown and pass it when clicked as a parameter to api in other funct

Time:01-24

How can I display only one type of value ${clickedNames.name_BG}, but on click get the second type of value ${clickedNames.name}

// Create a function that will insert the data into our legends UL in dropdown
    function listDataNames(dataStation) {
      // Loop through each result and append the data.
      dataStation.floodguard_stations.rows.map(function (clickedNames) {
        const fillNames = `
        <li><a  href="#">${clickedNames.name_BG} - ${clickedNames.name}</a></li>`;
        const item = document.createElement('li');
        item.innerHTML = fillNames;
        list.appendChild(item);
      });
      // Finally append all the data to the UL.
      ulNames.appendChild(list);
    }

In this function I get the data from API then I import two items in the drop down menu.

On click I want to pass the clicked value to this function on apiUrl:

    async function getMikeFWData() {
    const apiUrl = "http://I want to pass the clicked value from dropdown here"

    const response = await fetch(apiUrl)
    const mikefwdata = await response.json()

    const mikefwdate = mikefwdata.floodguard_mikefw.rows.map((x) => x.date)
    console.log(mikefwdate)
    const mikefwvalue = mikefwdata.floodguard_mikefw.rows.map((x) => x.level)
    console.log(mikefwvalue)

    mikeFWLabelChart = mikefwdate;
    mikeFWDataChart = mikefwvalue;
}

I am adding this picture for reference:

I want the values from 1 to be only visible on the dropdown (${clickedNames.name_BG}), but the values from 2 (${clickedNames.name})to be submitted as a parameter when clicked.

image

CodePudding user response:

Mdn Using data attributes

const li = document.querySelectorAll("li");
for (let i = 0; i < li.length; i  ) {
  li[i].addEventListener("click", (event) => {
    console.log(event.target.getAttribute("data-name"));
  });
}
li {
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <ul>
      <li data-name="item 1">item 1</li>
      <li data-name="item 2">item 2</li>
      <li data-name="item 3">item 3</li>
    </ul>

    <script>
     
    </script>
  </body>
</html>

You can store data which needs to pass in API in data-attribute

For example:

const fillNames = `
    <li><a  href="#" data-name="${clickedNames.name}">${clickedNames.name_BG} - ${clickedNames.name}</a></li>`;

so that it can be fetched when li is clicked

element.getAttribute("data-name")
  • Related