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

时间:2019-02-13 17:04:26

标签: javascript dom dom-events

我尝试从getSelectedCurrency函数返回当前选择的选项,默认情况下,选择货币选项被选中但被禁用。现在,我试图使函数仅在select元素中还有其他选项并且select元素更改时才返回当前选择的选项。

我尝试添加一个onchange事件侦听器,但由于事件侦听器默认情况下未定义返回值,因此我无法向该函数本身返回任何内容,因此在调用getSelectedCurrency时,它什么都不返回,这不是我想要的。

我还尝试将onchange事件监听器添加到populateCurrencies函数中,以便足够早地注册事件。...但是当我在声明之后立即调用getSelectedCurrency()时(并且在声明populateCurrencies()之后,它仅返回默认值(即选择货币文本)

<!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>

我希望调用getSelectedCurrency应该返回当前选择的选项,并且当发生更改时,它也应该返回该更改,但它只返回默认值。

1 个答案:

答案 0 :(得分:0)

在这里做了大量的整理工作,您多次选择了控件,还获得了selectvalue而不是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();的转换。

现在可以开始添加API调用代码了。

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>
   String completeURL = scBaseURL+"/"+scBasePath;
   URI uri = URI.create(completeURL.replace(" ","%20").replace("#","%23"));
   System.out.println(uri.toString());