Как использовать тег ввода, чтобы принять пользовательский ввод и вернуть значение с помощью JavaScript? - PullRequest
0 голосов
/ 24 декабря 2018

Я пытаюсь создать калькулятор бюджета, который принимает пользовательский ввод для различных переменных и возвращает новое значение после расчета.

Я пытался использовать тег ввода для получения значений для различных переменных и вычисленияРезультат с использованием функции JavaScript, которая отображает, возвращает результат в качестве значения другого входного тега.Я новичок в программировании, поэтому я не уверен, что это правильный путь.

var inc, rent, vloan, hins, vins, cc, loan, food, gas, entertainment, spending, result;

function calculate() {
  inc = document.getElementById("income").value;
  rent = document.getElementById("rent").value;
  vloan = document.getElementById("vloan").value;
  hins = document.getElementById("hinsurance").value;
  vins = document.getElementById("vinsurance").value;
  cc = document.getElementById("creditcard").value;
  loan = document.getElementById("loan").value;
  food = document.getElementById("food").value;
  gas = document.getElementById("gas").value;
  entertainment = getElementById("entertainment").value;
  spending = getElementById("spending").value;

  return document.getElementById("result").value = inc - rent - vloan - hins - vins - cc - loan - food - gas - entertainment - spending;
}
<div id="form2">
  Enter your income:<br>
  <input type="text" id="income"><br> Mortgage/Rent:<br>
  <input type="text" id="rent"><br> Vehicle Loan:<br>
  <input type="text" id="vloan"><br> Home Insurance:<br>
  <input type="text" id="hinsurance"><br> Vehicle Insurance:<br>
  <input type="text" id="vinsurance"><br> Credit Card:<br>
  <input type="text" id="creditcard"><br> Other Loans:<br>
  <input type="text" id="loan"><br> Groceries:<br>
  <input type="text" id="food"><br> Gas/Public Transport:<br>
  <input type="text" id="gas"><br> Cable/Internet:<br>
  <input type="text" id="entertainment"><br> Spending Money:<br>
  <input type="text" id="spending"><br>
  <button id="cb" onclick="calculate()">Calculate</button>
  <div id="answer">
    <p>It is suggested that 20% of your income be allocated towards a savings account</p>
    <input id="result" type="text" value="">
  </div>
</div>

Я ожидал, что результат после арифметической операции будет отображаться в последнем поле ввода с тегом id "result"

Ответы [ 2 ]

0 голосов
/ 24 декабря 2018

Вы забыли добавить документ.

раньше:

 entertainment = getElementById("entertainment").value;
 spending = getElementById("spending").value;

сейчас: (изменить на это)

entertainment = document.getElementById("entertainment").value;
spending = document.getElementById("spending").value;
0 голосов
/ 24 декабря 2018

Входные значения имеют тип string.Вы должны преобразовать их в число перед выполнением любой арифметической операции.Вы можете использовать parseFloat().

inc = parseFloat(document.getElementById("income").value);
.....
.....

Вы также забыли ссылаться на объект document в следующих выражениях:

entertainment = getElementById("entertainment").value;
spending = getElementById("spending").value;

Вам также не нужно return что-нибудь из функции.

Пример рабочего кода:

var inc, rent, vloan, hins, vins, cc, loan, food, gas, entertainment, spending, result;
function calculate(){
   inc = parseFloat(document.getElementById("income").value);
   rent = parseFloat(document.getElementById("rent").value);
   vloan = parseFloat(document.getElementById("vloan").value);
   hins = parseFloat(document.getElementById("hinsurance").value);
   vins = parseFloat(document.getElementById("vinsurance").value);
   cc = parseFloat(document.getElementById("creditcard").value);
   loan = parseFloat(document.getElementById("loan").value);
   food = parseFloat(document.getElementById("food").value);
   gas = parseFloat(document.getElementById("gas").value);
   entertainment = parseFloat(document.getElementById("entertainment").value);
   spending = parseFloat(document.getElementById("spending").value);
   document.getElementById("result").value = inc - rent - vloan - hins - vins - cc - loan - food - gas - entertainment - spending;
}
<div id="form2">
    Enter your income:<br>
    <input type="text" id="income"><br>
    Mortgage/Rent:<br>
        <input type="text" id="rent"><br>
    Vehicle Loan:<br>
    <input type="text" id="vloan"><br>
    Home Insurance:<br>
    <input type="text" id="hinsurance"><br>
    Vehicle Insurance:<br>
    <input type="text" id="vinsurance"><br>
    Credit Card:<br>
    <input type="text" id="creditcard"><br>
    Other Loans:<br>
    <input type="text" id="loan"><br>
    Groceries:<br>
    <input type="text" id="food"><br>
    Gas/Public Transport:<br>
    <input type="text" id="gas"><br>
    Cable/Internet:<br>
    <input type="text" id="entertainment"><br>
    Spending Money:<br>
    <input type="text" id="spending"><br>
    <button id="cb" onclick="calculate()">Calculate</button>
    <div id="answer">
         <p>It is suggested that 20% of your income be allocated towards a savings account</p>
    <input id="result" type="text" value="">
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...