Как написать функцию для расчета общей стоимости, очистки значений кнопок и отправки формы - PullRequest
0 голосов
/ 02 августа 2020

Все перепробовали, но похоже, что это не работает, и я новичок в javascript, любая помощь будет благодарна. Спасибо.

<html>

<body>
  <div id="form">
    <form name="this form" method="post" action="">
      <label> Item description</label>
      <input type="text" name="Item description" value="Red copper bowl" />
      <label>Quantity</label>
      <input type="number" name="quantity" value="1" />
      <label> Price</label>
      <input type="number" name="price" value="$450" readonly="" />
      <label>total price</label>
      <input type="Number" name="" value="" />
      <input type="button" value="Calculate Total" onclick="calculate total()" />
      <input type="button" value="submit" on-submit="submit()" />
    </form>
  </div>

  <script type="text/JavaScript">
    function calculateTotal() { var totalPrice = "$450"; var Quantity = document.getElementById("quantity").value; var price = document.getElementById("price").value; total = quantity * price; alert("Quantity cannot be zero, blank or null"); alert("Price cannot be zero, blank or null"); document.getElementById("totalPrice").innerHTML = totalPrice; return; } function clearTotal() { document.getElementById("Quantity").innerHTML = ""; document.getElementById("price").innerHTML = ""; return; } function
    submit() { return confirm( "is the information correct ? \n ItemDescription = RedBowl nQuantity = 1 nPrice = $450" ); }
  </script>
</body>

</html>

Ответы [ 2 ]

2 голосов
/ 02 августа 2020

Итак ... с вашим кодом бесчисленное множество проблем, но самое главное - читабельность. Пожалуйста, научитесь структурировать свой код.

несколько ошибок, на которые стоит обратить внимание:

  1. Нет метода 'on-submit'
  2. Прочтите соглашение об именах JS функций, так как «Calculate total ()» не является допустимым именем, которое вы используете для кнопки вычисления итогов.
  3. Вы пытаетесь получить элементы по идентификаторам но вы забыли его назначить.
  4. Снова соглашение об именах: «Количество» используется для хранения значения поля ввода количества, но вы использовали «количество» в вычисление.
  5. вы не можете установить внутренний Html для поля ввода.
  6. вы присвоили строковое значение для 'totalPrice', а затем использовали то же самое при умножении.

<html>

<body>
  <div id="form">
    <form name="this form" method="post" action="">
      <label> Item description</label>
      <input type="text" name="Item description" value="Red copper bowl" />
      <label>Quantity</label>
      <input type="number" id="quantity" name="quantity" value="1" />
      <label> Price</label>
      <input type="number" id="price" name="price" value="450" readonly="" />
      <label>total price</label>
      <input type="number" id="totalPrice" name="" value="450" />
      <input type="button" value="Calculate Total" onclick="calculateTotal()" />
      <input type="button" value="submit" onclick="submit()" />
       <input type="button" value="reset" onclick="clearTotal()" />
    </form>
  </div>

  <script type="text/JavaScript">
    function calculateTotal() { 
      //const totalPrice = "450";
      let quantity = document.getElementById("quantity").value; 
      let price = document.getElementById("price").value;
      let total = quantity * price;
      console.log(total)
      document.getElementById("totalPrice").value = total; 
    }
    
    function clearTotal() { 
      document.getElementById("quantity").value = 1;
      document.getElementById("totalPrice").value = 450; 
    } 
    function submit() { 
        return window.confirm( "is the information correct ? \n ItemDescription = RedBowl nQuantity = 1 nPrice = $450" ); 
    }
  </script>
  
</body>

</html>

и последнее, но не менее важное: https://www.w3schools.com/js/js_conventions.asp

0 голосов
/ 02 августа 2020
function calculateTotal() { 
    var totalPrice = "$450"; 
    
    //case matters as in "total = quantity * price <- quantity is lowercase
    //var Quantity = document.getElementById("quantity").value; 
    var quantity = document.getElementById("quantity").value; 
    
    var price = document.getElementById("price").value; 
    total = quantity * price; 
    alert("Quantity cannot be zero, blank or null"); 
    alert("Price cannot be zero, blank or null"); 

    //do you want the value from "total = quantity * price"? or the "var totalPrice = "$450""?
    document.getElementById("totalPrice").innerHTML = totalPrice; <- you probably want "total" not "total price"
    return; 
} 

function clearTotal() 
{ 
    document.getElementById("Quantity").innerHTML = ""; 
    document.getElementById("price").innerHTML = ""; 
    return; 
} 

function submit() 
{ 
    return confirm( "is the information correct ? \n ItemDescription = RedBowl nQuantity = 1 nPrice = $450" ); 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...