【问题标题】:How do I calculate income and expense in an expense tracker JavaScript如何在费用跟踪器 JavaScript 中计算收入和费用
【发布时间】:2023-02-09 18:09:18
【问题描述】:

我正在尝试在另一个函数的对象中添加选中的单选按钮的值。 但是,没有添加任何内容,也没有返回错误。

我正在构建一个费用跟踪器并添加这些值(收入或费用)在我的计算中很重要。

Nb:当我尝试在捕获选中值的函数中使用 console.log 时,它工作得很好,但是当我尝试将该值添加到另一个函数中的数组对象时,没有添加任何内容。

const TransactionType = document.getElementsByName('selector');

addbtn.addEventListener('click', function() {
  if (expense.value == '' || amount.value == '' || date.value == '') {
    alert('Please fill all the fields!!!');
    return;
  } else {
    const userExpense = {
      id: generateID(),
      type: getTransactionType(), // here is the problem nothing is added
      date: date.value,
      expense: expense.value,
      amount: amount.value
    };
    userInput.push(userExpense);
    localStorage.setItem('data', JSON.stringify(userInput));
    location.reload();
  }
});

function getTransactionType() {
  TransactionType.forEach(item => {
    if (item.checked) {

      return item.value;
    }
  });
}
<!-- radio buttons to choose the type of transaction -->
<div class="container">
  <h3>Select the type of transaction:</h3>
  <ul>
    <li>
      <input type="radio" id="type-income" name="selector" value="income">
      <label for="type-income">Income</label>
    </li>

    <li>
      <input type="radio" id="type-expense" name="selector" value="expense">
      <label for="type-expense">Expense</label>
    </li>
    <!-- <button onclick=" getTransactionType()">see value</button> -->
  </ul>
</div>

【问题讨论】:

  • 1.代码不完整。没有 addbtn,也没有显示 localStorage 2 的处理。我想制作一个 sn-p,但您使用的是此处不支持的 localStorage。无论如何,你为什么要重新加载页面?完全没有必要!
  • TransactionType.forEach(item =&gt; { if (item.checked) { return item.value; } });什么都不做。 return 语句在 forEach 中没有意义。你可能打算使用这个:const getTransactionType = () =&gt; document.querySelectorAll('[name=selector]:checked')[0].value;

标签: html javascript-objects


【解决方案1】:

代码不完整。没有 addbtn 也没有显示 localStorage 的处理

你为什么要重新加载?

TransactionType.forEach(item => { 
   if (item.checked) {
     return item.value;
   }
}); 

什么也没做。

return 语句在 forEach 中没有意义。

这是一个更简单的方法:我使用委托。

没有必要测试任何东西都被检查,因为你使用无线电。如果您使用复选框,则需要更多代码。

const getTransactionType = () => document.querySelectorAll('[name=selector]:checked')[0].value;

document.querySelector('.container').addEventListener('click', () => {
  console.log(getTransactionType())
})
<!-- radio buttons to choose the type of transaction -->
<div class="container">
  <h3>Select the type of transaction:</h3>
  <ul>
    <li>
      <input type="radio" id="type-income" name="selector" value="income">
      <label for="type-income">Income</label>
    </li>

    <li>
      <input type="radio" id="type-expense" name="selector" value="expense">
      <label for="type-expense">Expense</label>
    </li>
  </ul>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-12
    • 2020-03-13
    • 2022-11-10
    • 2018-06-14
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    相关资源
    最近更新 更多