简体   繁体   English

我如何使getSelectedCurrency仅在使用选项填充了select元素时运行

[英]How do I make getSelectedCurrency run only when the select element has been populated with options

I'm trying to return the currently selected option from the getSelectedCurrency function by default the select currency option is selected but disabled. 我试图从getSelectedCurrency函数返回当前选择的选项,默认情况下,选择货币选项被选中但被禁用。 Now I'm trying to make the function return the currently selected option only when there are other options in the select elements and when the select element changes. 现在,我试图使函数仅在select元素中还有其他选项并且select元素更改时才返回当前选择的选项。

I tried adding an onchange Event listener but I can't return anything to the function itself as eventlisteners return undefined by default, so by the time getSelectedCurrency is called, it returns nothing which is not what I want. 我尝试添加一个onchange事件侦听器,但由于事件侦听器默认情况下未定义返回值,因此我无法向该函数本身返回任何内容,因此在调用getSelectedCurrency ,它什么都不返回,这不是我想要的。

I also tried to add the onchange event listener to the populateCurrencies function so as to register the event early enough.... but when I call getSelectedCurrency() right after declaring it (and after declaring populateCurrencies() ) it returns only the default (ie select currency text) 我还尝试将onchange事件侦听器添加到populateCurrencies函数,以便足够早地注册该事件。...但是当我在声明它之后(并且在声明populateCurrencies()之后getSelectedCurrency()调用getSelectedCurrency() )时,它仅返回默认值(即选择货币文字)

<!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>Mini App</title>

    <style>
        body{
            background-color:#fff;
            margin:15px;
            }
       .select{
            margin-top:50px;
        }
       .conversion{
            margin:25px 0px;
        }
       .btn{
            width:100%;
            font-size:1.2rem;
            padding:1rem;
           }
    </style>
</head>
<body>
    <h1>Naira Converted</h1>
    <div class="select-currency select">
        <select class="select-text">
            <option selected disabled>Select Currency</option>
        </select>
        <button type="submit" class="btn">In Naira</button>
        <div class="conversion mdc-elevation--z3"></div> 
        <div class="messages"></div>
    </div>
<script>
const currencies = [{
    id: 'USD', name: 'US Dollars'
  }, {
    id: 'UGX', name: 'Ugandan Shillings'
  }, {
    id: 'KES', name: 'Kenyan Shillings'
  }, {
    id: 'GHS', name: 'Ghanian Cedi'
  }, {
    id: 'ZAR', name: 'South African Rand'
  }];

  const apiBase = 'https://free.currencyconverterapi.com/api/v6/';
  const api = (currency) => `
    ${apiBase}convert?q=${currency}_NGN&compact=ultra
  `;

  const toast = (msg) => {
    const toastr = document.querySelector('.messages');
    if(!toastr) return;

    toastr.textContent = msg;
    if(!toastr.classList.contains('on')) {
      toastr.classList.add('on');
    }
  };

  const doneToasting = () => {
    const toastr = document.querySelector('.messages');
    if(!toastr) return;

    toastr.textContent = '';
    toastr.classList.remove('on');
  };

  const conversionSucceeded = (apiResponse) => {
    if(!apiResponse) {
      toast(`nothing to display ...`);
      return;
    }

    const [value] = Object.values(apiResponse)

    const btn = document.querySelector('button');
    btn.removeAttribute('disabled');

    const display = document.querySelector('.conversion');
    const formatter = new Intl.NumberFormat(
      'en-NG', { style: 'currency', currency: 'NGN' }
    );

    display.textContent = formatter.format(value);
    doneToasting();
  };
 // declare populateCurrencies here      
  const populateCurrencies = ()=>{
    currencies.forEach((x)=>{
      let elt = document.querySelector('.select-text');
      let newElt = document.createElement('option');
      let newText = document.createTextNode(x.name);
      newElt.appendChild(newText);
      newElt.setAttribute('value',x.id);
      elt.appendChild(newElt);
    })
      let elt = document.querySelector('.select-text');
    elt.addEventListener('change',()=>{
       let currentlySelected =document.querySelector('[selected]');
       currentlySelected.removeAttribute('selected');
       elt.selectedOptions[0].setAttribute('selected','');
      console.log(getSelectedCurrency());
      },false)
    }
   const getSelectedCurrency=()=>{
    // here, determine and return the selected value 
    // of the SELECT element
    let currentlySelected= document.querySelector('.select-text');
    let value= currentlySelected.selectedOptions[0].textContent;
    return(value) ;
  };
  const selected = getSelectedCurrency();
  console.log(selected);
  const convert = (event) => {
    toast(`preparing to convert ...`);

    const btn = event ? 
          event.target : document.querySelector('button');

    const selected = getSelectedCurrency();

    if(!selected || selected.trim() === '' 
       || !currencies.map(c => c.id).includes(selected)) return;

    btn.setAttribute('disabled', 'disabled');
    toast(`converting ...`);

    const endpoint = api(selected);

    // make a GET fetch call to the endpoint
    // variable declared above, convert the response to JSON,
    // then call conversionSucceeded and pass the JSON data to it
  };

  const startApp = () => {
    // call populateCurrencies here
    populateCurrencies();
    // add a click listener to the button here
    document.querySelector('button').addEventListener('click',(event)=>       
    {convert(event)},false);
  };
  startApp();
        </script>
     </body>
</html>

I expect that calling getSelectedCurrency should return the currently selected option and when a change occurs it should also return that change also but it returns only the default. 我希望调用getSelectedCurrency应该返回当前选择的选项,并且当发生更改时,它也应该返回该更改,但它只返回默认值。

Done a bunch of tidy up here, you were selecting controls multiple times and also getting the text or your select rather than the value for conversion. 在这里做了大量的整理工作,您多次选择了控件,并且还获得了text或您select而不是转换value

Now its ready for you to add your API call code. 现在可以开始添加API调用代码了。

 const currencies = [{ id: 'USD', name: 'US Dollars' }, { id: 'UGX', name: 'Ugandan Shillings' }, { id: 'KES', name: 'Kenyan Shillings' }, { id: 'GHS', name: 'Ghanian Cedi' }, { id: 'ZAR', name: 'South African Rand' }]; const apiBase = 'https://free.currencyconverterapi.com/api/v6/'; const api = (currency) => `${apiBase}convert?q=${currency}_NGN&compact=ultra`; const toast = (msg) => { const toastr = document.querySelector('.messages'); if (!toastr) return; toastr.innerText = msg; toastr.classList.add('on'); }; const doneToasting = () => { const toastr = document.querySelector('.messages'); if (!toastr) return; toastr.innerText = ''; toastr.classList.remove('on'); }; const conversionSucceeded = (apiResponse) => { if (!apiResponse) { toast(`nothing to display ...`); return; } const [value] = Object.values(apiResponse) const btn = document.querySelector('button'); btn.removeAttribute('disabled'); const display = document.querySelector('.conversion'); const formatter = new Intl.NumberFormat( 'en-NG', { style: 'currency', currency: 'NGN' } ); display.innerText = formatter.format(value); doneToasting(); }; // declare populateCurrencies here const populateCurrencies = () => { let elt = document.querySelector('.select-text'); currencies.forEach((x) => { let newElt = document.createElement('option'); newElt.text = x.name; newElt.value = x.id; elt.add(newElt); }) elt.addEventListener('change', () => { console.log(getSelectedCurrency()); }, false) }; const getSelectedCurrency = () => { // here, determine and return the selected value // of the SELECT element let currentlySelected = document.querySelector('.select-text'); let value = currentlySelected.selectedOptions[0].value; return (value); }; const selected = getSelectedCurrency(); console.log(selected); const convert = (event) => { toast(`preparing to convert ...`); const btn = event ? event.target : document.querySelector('button'); const selected = getSelectedCurrency(); toast(`converting for currency: ${selected}`); if (!selected || selected.trim() === '' || !currencies.map(c => c.id).includes(selected)) return; btn.setAttribute('disabled', 'disabled'); toast(`converting ...`); const endpoint = api(selected); // Need to add your API call now. console.log(endpoint); // make a GET fetch call to the endpoint // variable declared above, convert the response to JSON, // then call conversionSucceeded and pass the JSON data to it }; const startApp = () => { // call populateCurrencies here populateCurrencies(); // add a click listener to the button here document.querySelector('button').addEventListener('click', (event) => { convert(event) }, false); }; startApp(); 
 body { background-color: #fff; margin: 15px; } .select { margin-top: 50px; } .conversion { margin: 25px 0px; } .btn { width: 100%; font-size: 1.2rem; padding: 1rem; } 
 <!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>Mini App</title> </head> <body> <h1>Naira Converted</h1> <div class="select-currency select"> <select class="select-text"> <option selected disabled>Select Currency</option> </select> <button type="submit" class="btn">In Naira</button> <div class="conversion mdc-elevation--z3"></div> <div class="messages"></div> </div> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 仅当元素未与之交互时,才如何为其设置动画? - How do I animate an element only if it has not been interacted with? 如何制作 <div> 仅在某个 <select>下拉选项被选中?该<select>用ng-repeat指令填充选项 - How to make a <div> show only when a certain <select> dropdown option is selected? The <select> options are populated with the ng-repeat directive 如何在单击其他元素时显示元素? - How do I show an element when another element has already been clicked? 元素加载后如何运行函数? - How do you run a function after an element has been loaded? make protractor等待select元素在选择另一个Select元素中的选项时填充选项 - make protractor wait for the select element to get populated with options on selecting a option in another Select element 设置PHP查询字符串后,如何使jQuery脚本运行? - How do I make a jQuery script run once a PHP query string has been set? 如果requireJS模块在$上设置了全局变量,那么仅在分配了全局变量后,如何执行模块代码? - if a requireJS module sets a global on $, how do I execute the module code only when the global has been assigned? 我如何使嵌套循环仅在解决了异步函数之后才能继续,或者如何将“ .then”扩展到范围之外 - How do I make a nested loop continue only after a asynchronous function has been resolved or how do I extend “.then” beyond the scope 如何选择尚未创建的元素? - How do I select an element that hasn't been created yet? 首先填充另一个下拉框时,如何显示新的下拉框? - How do I make new drop down boxes appear when another one has been filled in first?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM