Создать калькулятор "экономии времени" с динамическими фигурами - PullRequest
0 голосов
/ 13 сентября 2011

Мне было поручено создать динамический калькулятор на веб-странице.

Он будет состоять из следующего:

  1. Несколько цифр, которые будут введены через бэкэнд (Wordpress).
  2. Несколько областей ввода, в которые клиент будет вводить цифры.
  3. И несколько цифр, которые будут меняться в зависимости от того, что вводит клиент.

Будет несколькорасчеты меняют цифры на странице.

Я могу легко выводить цифры из WP, это всего лишь пункты 2 и 3, с которыми я борюсь.Какой лучший способ подойти к этому?Кто-нибудь может опубликовать несколько простых примеров, включающих 3 пункта выше?

Один важный элемент заключается в том, что он должен пересчитывать цифры на лету - поэтому не нужно нажимать кнопки отправки или что-либо в этом направлении.

Ответы [ 2 ]

1 голос
/ 13 сентября 2011

Точка 1

<script>
var unitPrice = <?php echo $unitPrice; ?>;
...
</script>

Точка 2

<input type="text" id="quantity" onkeyup="updateTotal();/>

Точка 3

<span id="totalPrice"></span>

<script>
function updateTotal() {
    var quantity   = parseInt(document.getElementById('quantity').value, 10);
    if(isNaN(quantity)) quantity = 0;
    var totalPrice = unitPrice * quantity;
    document.getElementById('totalPrice').innerText = totalPrice;
}
</script>

Демо здесь .

0 голосов
/ 13 сентября 2011

Вот простой калькулятор, который я только что скомбинировал, который вычисляет другие свойства круга из любого одного свойства.Он использует событие onkeyup, поэтому значения обновляются по мере ввода.Он ни в коем случае не идеален (даже не уверен на 100% в математике), но дело не в этом, а в том, чтобы продемонстрировать, как выполнять вычисления и обновлять отображение в реальном времени, и, надеюсь, это даст вам толчокправильное направление.

Слишком сложно объяснить здесь очень подробно, поэтому поиграйте с ним и задайте конкретные вопросы, и я отвечу на них, как смогу ...

ОБНОВЛЕННЫЙ КОД

<html>

  <head>
    <title>Circle calculator</title>
    <script type="text/javascript">

      var radius, diameter, circumference, area, sphereVolume, lastRadius, lastDiameter, lastCircumference, lastArea, lastSphereVolume;

      function updateDisplays () {
        // This function updates the displayed values
        document.getElementById('radius_input').value = (isNaN(radius)) ? '0.0' : ((radius.toString().split('.').length == 1) ? radius.toString()+'.0' : radius);
        document.getElementById('diameter_input').value = (isNaN(diameter)) ? '0.0' : ((diameter.toString().split('.').length == 1) ? diameter.toString()+'.0' : diameter);
        document.getElementById('circumference_input').value = (isNaN(circumference)) ? '0.0' : ((circumference.toString().split('.').length == 1) ? circumference.toString()+'.0' : circumference);
        document.getElementById('area_input').value = (isNaN(area)) ? '0.0' : ((area.toString().split('.').length == 1) ? area.toString()+'.0' : area);
        document.getElementById('spherevolume_input').value = (isNaN(sphereVolume)) ? '0.0' : ((sphereVolume.toString().split('.').length == 1) ? sphereVolume.toString()+'.0' : sphereVolume);
        // Track the last values
        lastRadius = (isNaN(radius)) ? 0 : radius;
        lastDiameter = (isNaN(diameter)) ? 0 : diameter;
        lastCircumference = (isNaN(circumference)) ? 0 : circumference;
        lastArea = (isNaN(area)) ? 0 : area;
        lastSphereVolume = (isNaN(sphereVolume)) ? 0 : sphereVolume;
      }

      window.onload = function () {

        // All these functions calculate the other values based on the one that has changed

        document.getElementById('radius_input').onkeyup = function () {
          radius = parseFloat(this.value);
          if (lastRadius == radius) {
            return;
          }
          diameter = radius * 2;
          circumference = Math.PI * diameter;
          area = Math.PI * Math.pow(radius, 2);
          sphereVolume = (4 / 3) * Math.PI * Math.pow(radius, 3);
          updateDisplays();
        };

        document.getElementById('diameter_input').onkeyup = function () {
          diameter = parseFloat(this.value);
          if (lastDiameter == diameter) {
            return;
          }
          radius = diameter / 2;
          circumference = Math.PI * diameter;
          area = Math.PI * Math.pow(radius, 2);
          sphereVolume = (4 / 3) * Math.PI * Math.pow(radius, 3);
          updateDisplays();
        };

        document.getElementById('circumference_input').onkeyup = function () {
          circumference = parseFloat(this.value);
          if (lastCircumference == circumference) {
            return;
          }
          diameter = circumference / Math.PI;
          radius = diameter / 2;
          area = Math.PI * Math.pow(radius, 2);
          sphereVolume = (4 / 3) * Math.PI * Math.pow(radius, 3);
          updateDisplays();
        };

        document.getElementById('area_input').onkeyup = function () {
          area = parseFloat(this.value);
          if (lastArea == area) {
            return;
          }
          radius = Math.sqrt(area / Math.PI);
          diameter = radius * 2;
          circumference = Math.PI * diameter;
          sphereVolume = (4 / 3) * Math.PI * Math.pow(radius, 3);
          updateDisplays();
        };

        document.getElementById('spherevolume_input').onkeyup = function () {
          sphereVolume = parseFloat(this.value);
          if (lastSphereVolume == sphereVolume) {
            return;
          }
          radius = Math.pow((sphereVolume / Math.PI) * (3/4), 1/3);
          diameter = radius * 2;
          area = Math.PI * Math.pow(radius, 2);
          circumference = Math.PI * diameter;
          updateDisplays();
        };

      };
    </script>
    <style>
      #title {
        margin-bottom: 20px;
        font-weight: bold;
      }
      td.property_name {
        text-align: right;
        padding-right: 10px;
      }
      td.property_formula {
        padding-left: 10px;
        font-weight: bold;
      }
    </style>
  </head>

  <body>
    <div id="title">Circle Calculator</div>
    <table>
      <tr>
        <td class="property_name">Radius:</td>
        <td><input type="text" id="radius_input" value="0.0" /> cm</td>
        <td class="property_formula"></td>
      </tr>
      <tr>
        <td class="property_name">Diameter:</td>
        <td><input type="text" id="diameter_input" value="0.0" /> cm</td>
        <td class="property_formula">2r</td>
      </tr>
      <tr>
        <td class="property_name">Circumference:</td>
        <td><input type="text" id="circumference_input" value="0.0" /> cm</td>
        <td class="property_formula">2&#960;r</td>
      </tr>
      <tr>
        <td class="property_name">Area:</td>
        <td><input type="text" id="area_input" value="0.0" /> cm<sup>2</sup></td>
        <td class="property_formula">&#960;r<sup>2</sup></td>
      </tr>
      <tr>
        <td class="property_name">Volume of Sphere:</td>
        <td><input type="text" id="spherevolume_input" value="0.0" /> cm<sup>3</sup></td>
        <td class="property_formula"><sup>4</sup>&frasl;<sub>3</sub>&#960;r<sup>3</sup></td>
      </tr>
    </table>
  </body>

</html>

РЕДАКТИРОВАТЬ

Гораздо более простой пример, который просто выполняет 1 добавление:

<html>

  <head>
    <title>Simple Calculator</title>
    <script type="text/javascript">

      window.onload = function () {
      // All code here is executed once the document has finished loading

        // Assign a function to num1's onkeyup event
        document.getElementById('num1').onkeyup = function () {
          // Declare the variables
          var num1, num2;
          // Get the values in variables with the correct type for calculations
          num1 = parseFloat(this.value);
          num2 = parseFloat(document.getElementById('num2').value);
          // Update the answer display
          document.getElementById('answer').innerHTML = num1 + num2;
        };

        // Assign a function to num2's onkeyup event
        document.getElementById('num2').onkeyup = function () {
          // Declare the variables
          var num1, num2;
          // Get the values in variables with the correct type for calculations
          num1 = parseFloat(document.getElementById('num1').value);
          num2 = parseFloat(this.value);
          // Update the answer display
          document.getElementById('answer').innerHTML = num1 + num2;
        };

      };

    </script>
  </head>

  <body>
    <input type="text" id="num1" size="4" value="0" /> + <input type="text" id="num2" size="4" value="0" /> = <span id="answer">0</span>
  </body>

</html>
...