Как рассчитать данные AJAX, которые добавляются в HTML Div - PullRequest
0 голосов
/ 13 октября 2018

У меня есть поиск везде, и мне кажется, что я ничего не могу найти по этому поводу, у меня есть ajax, который отправляет данные в мой php-файл, который затем получает данные из базы данных и представляется в виде div

ajax

$(document).ready(function () {

        $("#addForm").on('submit', function (e) {
            // widthMeas and Drop Meas are just the selection of cm/in/m ect

            let Width = document.getElementById('blindWidth').value;
            let widthMeas = document.getElementById('widthMeas').value;

            let height = document.getElementById('height').value;
            let dropMeas = document.getElementById('dropMeas').value;

            let Type = document.getElementById('Type').value

            let quantity = document.getElementById('quantity').value

            $.ajax({
                url:"converter.php",
                method: "post",
                data:{
                    Width: Width,
                    widthMeas: widthMeas,
                    Drop: Drop,
                    dropMeas: dropMeas,
                    Type: Type,
                    quantity: quantity
                },
           success:function (data) {
           console.log(data);
           $('#quote').append(data);
           $('#addBlindForm')[0].reset();
           $('#quoteModal').modal('hide');
           $('#quoteContainer').show();
          }
      });
});

php file

$output .= "
             <tr>
                <td>".$InputWidth."".$widthMeas." x ".$InputDrop."".$dropMeas." </td>
                <td>".$Type."</td>
                <td>".$quantity."</td>
                <td>£ ".$price."</td>
             </tr><br>
                         ";
            echo $output;
            break;

Я хочу знать, как я могу добавить все итоги в режиме реального времени после добавления каждого нового элемента в «цитатный div», который должен отображаться

ширина высота тип количество цена 1 см х 1 см доска 12 44

всего 44,00

Ответы [ 2 ]

0 голосов
/ 14 октября 2018

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

 $('.calculate').click(function () {
       let total = 0;
       $(".price").each(function () {
          total = total + parseInt($(this).val());
       });

      $('.quote').html(total);
 });
0 голосов
/ 13 октября 2018

<!DOCTYPE html>
<html lang="pt-br">
<meta charset="utf-8" />

<head>
    <title>Vote</title>

</head>

<body>
    <div>
        Width :
        <input type="number" name="" id="blindWidth">
        <br> Height :
        <input type="number" name="" id="height">
        <br> Type :
        <input type="text" name="" id="Type">
        <br> Quantity :
        <input type="number" name="" id="quantity">
        <br>
        <div id="priceTag">Fill in the inputs above</div>
        <div id="dimensions"></div>

    </div>
    <script type="text/javascript">
        function calcPrice(quantityValue) {
            quantityValue = quantityValue || 0;
            let basePrice = 12;
            totalPrice = 12 * quantityValue;

            if (totalPrice > 0) {
                document.getElementById('priceTag').innerText = `Price : ${totalPrice}`;
            } else {
                document.getElementById('priceTag').innerText = ``;
            }
        }

        function calcDimensions(heightValue, widthValue) {
            let dimensions = heightValue * widthValue;
            if (dimensions > 0) {
                document.getElementById('dimensions').innerText = `Dimensions : ${dimensions}`;
            } else {
                document.getElementById('dimensions').innerText = ``;
            }
        }
        let width = document.getElementById('blindWidth');
        let height = document.getElementById('height');
        let quantity = document.getElementById('quantity');

        width.addEventListener('keyup', () => {
         //   console.log('typing on width');
            let widthValue = width.value || 0;
            let heightValue = height.value || 0;
            let quantityValue = quantity.value || 0;

            calcDimensions(widthValue, heightValue);
            calcPrice(quantityValue);

        })

        height.addEventListener('keyup', () => {
           // console.log('typing on height');
            let widthValue = width.value || 0;
            let heightValue = height.value || 0;
            let quantityValue = quantity.value || 0;

            calcDimensions(widthValue, heightValue);
            calcPrice(quantityValue);

        })

        quantity.addEventListener('keyup', () => {
           // console.log('typing on quantity');
            let widthValue = width.value || 0;
            let heightValue = height.value || 0;
            let quantityValue = quantity.value || 0;

            calcDimensions(widthValue, heightValue);
            calcPrice(quantityValue);

        })
    </script>
</body>

</html>

Чтобы выполнять вычисления в реальном времени, используйте JavaScript-EventListeners.

Чтобы узнать больше о EventListeners, см. Эту статью

Вот HTML-код, нажмите на RUN SNIPPET, чтобы увидеть, как он работает.

Спасибо.

                <!DOCTYPE html>
            <html lang="pt-br">
            <meta charset="utf-8" />

            <head>
                <title>Vote</title>

            </head>

            <body>
                <div>
                    Width :
                    <input type="number" name="" id="blindWidth">
                    <br> Height :
                    <input type="number" name="" id="height">
                    <br> Type :
                    <input type="text" name="" id="Type">
                    <br> Quantity :
                    <input type="number" name="" id="quantity">
                    <br>
                    <div id="priceTag">Fill in the inputs above</div>
                    <div id="dimensions"></div>

                </div>
                <script type="text/javascript">
                    function calcPrice(quantityValue) {
                        quantityValue = quantityValue || 0;
                        let basePrice = 12;
                        totalPrice = 12 * quantityValue;

                        if (totalPrice > 0) {
                            document.getElementById('priceTag').innerText = `Price : ${totalPrice}`;
                        } else {
                            document.getElementById('priceTag').innerText = ``;
                        }
                    }

                    function calcDimensions(heightValue, widthValue) {
                        let dimensions = heightValue * widthValue;
                        if (dimensions > 0) {
                            document.getElementById('dimensions').innerText = `Dimensions : ${dimensions}`;
                        } else {
                            document.getElementById('dimensions').innerText = ``;
                        }
                    }
                    let width = document.getElementById('blindWidth');
                    let height = document.getElementById('height');
                    let quantity = document.getElementById('quantity');

                    width.addEventListener('keyup', () => {
                        console.log('typing on width');
                        let widthValue = width.value || 0;
                        let heightValue = height.value || 0;
                        let quantityValue = quantity.value || 0;

                        calcDimensions(widthValue, heightValue);
                        calcPrice(quantityValue);

                    })

                    height.addEventListener('keyup', () => {
                        console.log('typing on height');
                        let widthValue = width.value || 0;
                        let heightValue = height.value || 0;
                        let quantityValue = quantity.value || 0;

                        calcDimensions(widthValue, heightValue);
                        calcPrice(quantityValue);

                    })

                    quantity.addEventListener('keyup', () => {
                        console.log('typing on quantity');
                        let widthValue = width.value || 0;
                        let heightValue = height.value || 0;
                        let quantityValue = quantity.value || 0;

                        calcDimensions(widthValue, heightValue);
                        calcPrice(quantityValue);

                    })
                </script>
            </body>

            </html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...