如何通过以下代码中的功能getSelectedCurrency()获取所选元素

时间:2019-02-13 11:54:52

标签: javascript dom

我正在构建一个货币换算器应用程序,并且试图在代码中使用getSelectedCurrency()函数选择货币。当我在代码中管理日志值时,它返回文本,但不满足TDD测试返回所选货币的要求

我尝试使用事件监听器,但是事件监听器通常返回未定义

 // 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','');
      },false)
    }

   function getSelectedCurrency(){
    // here, determine and return the selected value 
    // of the SELECT element
    let currentlySelected= document.querySelector('.select-text');
    let value= currentlySelected.selectedOptions[0].text;
    return((String(value)));
  };
  const convert = (event) => {
    toast(`preparing to convert ...`);

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

    const selected = getSelectedCurrency();
    console.log(selected);

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

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

    const endpoint = api(selected);

我希望getSelectedCurrency()返回一个字符串,但不返回任何内容。

1 个答案:

答案 0 :(得分:0)

您以错误的方式选择了选项

function getSelectedCurrency(){
    // here, determine and return the selected value 
    // of the SELECT element
    let currentlySelected= document.querySelector('.select-text');
    let value= currentlySelected.options[currentlySelected.selectedIndex].textContent;
    if(value="")
    return false;
    else
    return value;
  };