Как я могу решить эту проблему, в полях Количество и Общая цена отображается пустой результат при выборе любого продукта из выпадающего списка? - PullRequest
0 голосов
/ 05 октября 2019

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

Материнская плата выбрана, все работает нормально, пока

Когда я нажимаю Выбрать материнскую плату, все поля становятся пустыми

Когда я выбираю количество веб-камеры, а общая стоимость не отображается, возникает проблема

<?php
include("includes/headerLinks.php");
include("includes/nav.php");
// include("includes/db.php");
// include("includes/header.php");
$connect = mysqli_connect("localhost", "root", "", "onlinequotation");
function motherboard_brand($connect)
{
     $output = '';
     $sql = "SELECT * FROM products WHERE category='Motherboard' AND status='Active'";
     $result = mysqli_query($connect, $sql);
     while($row = mysqli_fetch_array($result))
     {
          $output .= '<option value="'.$row["id"].'">'.$row["product_title"].'</option>';
     }
     return $output;
}
function processor_brand($connect)
{
     $output = '';
     $sql = "SELECT * FROM products WHERE category='Processor' AND status='Active'";
     $result = mysqli_query($connect, $sql);
     while($row = mysqli_fetch_array($result))
     {
          $output .= '<option value="'.$row["id"].'">'.$row["product_title"].'</option>';
     }
     return $output;
}
// for ram
function ram_brand($connect)
{
     $output = '';
     $sql = "SELECT * FROM products WHERE category='Ram' AND status='Active'";
     $result = mysqli_query($connect, $sql);
     while($row = mysqli_fetch_array($result))
     {
          $output .= '<option value="'.$row["id"].'">'.$row["product_title"].'</option>';
     }
     return $output;
}

// For Hardisk

function harddisk_brand($connect)
{
     $output = '';
     $sql = "SELECT * FROM products WHERE category='Hard-disk' AND status='Active'";
     $result = mysqli_query($connect, $sql);
     while($row = mysqli_fetch_array($result))
     {
          $output .= '<option value="'.$row["id"].'">'.$row["product_title"].'</option>';
     }
     return $output;
}

?>

    <hr class="offset-top">

    <div class="white">
        <div class="container checkout">
            <h1>Quotation Generator</h1>
            <hr class="offset-sm">
        </div>
    </div>
    <hr class="offset-md">

    <div class="container checkout">
        <form method="POST" name="myForm">

        <div class="row">
            <div class="col-md-12 white" style="border-radius:30px">
                <div class="checkout-cart">
                    <div class="content">
                      <!-- contact form -->
                            <div class="row">
                                <div class="col-md-4 col-md-offset-4">
                                    <div class="form-group">
                                        <label for="form_name">Firstname *</label>
                                        <input id="name" type="text" name="name" class="form-control" placeholder="Please enter your Name *">

                                    </div>
                                </div> 
                            </div>
                            <div class="row">
                                <div class="col-md-4 col-md-offset-4">
                                    <div class="form-group">
                                        <label for="form_lastname">Mobile *</label>
                                        <input id="mobile" type="text" name="mobile" class="form-control" placeholder="Please enter your Mobile# *">

                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 col-md-offset-4">
                                    <div class="form-group">
                                        <label for="form_lastname">Email *</label>
                                        <input id="email" type="email" name="email" class="form-control" placeholder="Please enter Email *">

                                    </div>
                                    <!-- <div id="error" style="text-align:center;display:none">Fill all the textboxes</div> -->
                                </div>

                            </div>

                      <!-- End contact form -->
                    <table class="table table-bordered table-striped">
                              <tr style="background-color:#00a1b4">
                                  <th>
                                      Name
                                  </th>
                                  <th>
                                      Products
                                  </th>
                                  <th >
                                      QUANTITY
                                  </th>
                                  <th>
                                      Per Item Price
                                  </th>
                                  <th>
                                      Total Price
                                  </th>
                              </tr>

                              <tr class="category motherboard" data-value="motherboard">
                                <td>
                                    <span>Motherboard</span>
                                </td> 
                                <td>
                                  <select name="motherboard" id="motherboard" style="min-width: 100%;" class="select" onchange="getPrice(event)">
                                    <option value="0">Select Motherboard</option>
                                    <?php echo motherboard_brand($connect); ?>
                                  </select>
                                </td>
                                <!-- QUANTITY -->
                                <td>
                                    <input type="number" min="0" name="email" class="quantity" oninput="setTotalPrice(event)"/>
                                </td>
                                <!-- per item price -->
                                <td>
                                    <input type="text"  readonly class="unit-price" >
                                </td>
                                <!-- Total Price -->
                                <td>
                                    <input type="text" readonly  class="total-price">
                                </td>
                            </tr>

                            <tr class="category processor" data-value="processor">
                                <td>
                                    <span>Processor</span>
                                </td> 
                                <td>
                                  <select name="processor" id="processor" style="min-width: 100%;" class="select processors" onchange="getPrice(event)">
                                    <option>Select Processor</option>
                                    <!-- <?php echo processor_brand($connect); ?> -->
                                  </select>
                                </td>
                                <!-- QUANTITY -->
                                <td>
                                    <input type="number" min="0" name="email" class="quantity" oninput="setTotalPrice(event)"/>
                                </td>
                                <!-- per item price -->
                                <td>
                                    <input type="text"  readonly class="unit-price" >
                                </td>
                                <!-- Total Price -->
                                <td>
                                    <input type="text" readonly  class="total-price">
                                </td>
                            </tr>


                        <!-- End Processor Section -->


                        <!-- Start Ram Section -->
                              <tr class="category ram" data-value="ram">
                                <td>
                                    <span>Ram</span>
                                </td>
                                  <td>
                                    <select name="ram" id="rams" style="min-width: 100%;" class="select" onchange="getPriceRam(event)">
                                    <option id="ram1st">Select Ram</option>
                                      <!-- <?php echo ram_brand($connect); ?> -->
                                    </select>
                                  </td>
                                  <!-- QUANTITY -->
                                  <td>
                                      <input type="number" maxlength="6" min="0" min="10" name="email" class="quantity" oninput="setTotalPrice(event)"/>
                                  </td>
                                  <!-- per item price -->
                                  <br>
                                  <td>
                                      <input type="text"  readonly class="unit-price" >
                                  </td>
                                  <!-- Total Price -->
                                  <td>
                                      <input type="text" readonly  class="total-price">
                                  </td>
                              </tr>

                        <!-- End Ram Section -->

                         <!-- Start harddisk Section -->
                         <tr class="category harddisk" data-value="harddisk">
                                <td>
                                    <span>Harddisk</span>
                                </td>
                                  <td>
                                    <select name="harddisk" id="" style="min-width: 100%;" class="select" onchange="getPrice(event)">
                                      <option>Select Harddisk</option>
                                      <?php echo harddisk_brand($connect); ?>
                                    </select>
                                  </td>
                                  <!-- QUANTITY -->
                                  <td>
                                      <input type="number" maxlength="6" min="0" min="10" name="email" class="quantity" oninput="setTotalPrice(event)"/>
                                  </td>
                                  <!-- per item price -->
                                  <br>
                                  <td>
                                      <input type="text"  readonly class="unit-price" >
                                  </td>
                                  <!-- Total Price -->
                                  <td>
                                      <input type="text" readonly  class="total-price">
                                  </td>
                              </tr>
                        <!-- End Harddisk Section -->
                              <tr>
                              <td colspan="4" align="right"><b>Total Price : </b></td>
                              <td id="TotalPrice"></td>
                              </tr>

                    </table>



                    </div>
                </div>
            <hr class="offset-lg hidden-xs">

            <div class="col-sm-12">
                <hr class="offset-md">
                <div class="row">
                    <div class="col-xs-6 col-md-4 col-md-offset-3">
                    <!-- onclick="submitQuote(event);" -->
                        <button class="btn btn-primary pull-right" type="button" onclick="submitQuote(event);" >Submit</button>
                    </div>
                </div>
                <hr class="offset-md">
            </div>
        </div>
        </form>
    </div>

    <hr class="offset-lg">
    <hr class="offset-sm">
  <?php
  // include("includes/footer.php");
  include("includes/jsLinks.php");
  ?>
  <!-- For Processor -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function getPrice(e){ 
e.preventDefault();
// grandtotal();
var id = $(e.target).val();
// console.log(id);
// ;unitPrice.value
let parent = e.target.parentNode.parentNode;
console.log(parent);
let parentt = e.target.parentNode;
// $("#selector option:selected");
console.log(parentt);
let category = parent.getAttribute("data-value");
// console.log(category);

$.ajax({
     url:"load_data.php",
     method:"POST",
     data:{id:id},
     success:function(data){
        //   console.log(data);
          let unitPrice = parent.querySelector("input.unit-price");
          // console.log(unitPrice);
          unitPrice.value = data;
          $(parent).attr("data-id", id);
          $(parent).attr("data-quantity", 1);
          if($('.select').find(":selected").val() == 0)
            {
                parent.querySelector("input.quantity").value = "";
                parent.querySelector("input.total-price").value = null;
            }
            else{
                parent.querySelector("input.quantity").value = 1;
                parent.querySelector("input.total-price").value = +data * 1;
            }
          grandtotal();
     }
   });
}

function setTotalPrice(e){
e.preventDefault();
// console.log(event.target);
let parent = e.target.parentNode.parentNode;
// console.log(parent);
let unitPrice = parent.querySelector("input.unit-price").value;
let quantity  = parent.querySelector("input.quantity").value;
$(parent).attr("data-quantity", quantity);
parent.querySelector("input.total-price").value = (+unitPrice) * (+quantity);
grandtotal();
}
// Grand Total
function grandtotal() {

var sum=0;
$('.total-price').each(function(){
var item_val=parseFloat($(this).val());
if(isNaN(item_val)){
  item_val=0;
}
sum+=item_val;
$('#TotalPrice').html(sum.toFixed(2));
});

}   

$("#motherboard").change(function(){
                var mid = $("#motherboard").val();
                // console.log(mid);
                $.ajax({
                    url: 'processor_data.php',
                    method: 'post',
                    data: 'mid=' + mid
                }).done(function(processors) {
                    // console.log(processors);
                    $('#processor').empty().append('<option>Select Processor</option>');
                    processors = JSON.parse(processors);

                    var htmll = '';
                    processors.forEach(function(processor) {
                        htmll += '<option value="' + processor.id + '">' + processor.product_title + '</option>';
                    })
                    $('#processor').append(htmll);
                });
            })
            function getPriceRam(e){
                                    e.preventDefault();
                                    grandtotal();
                                    var id = $(e.target).val();
                                    // console.log(id);
                                    let parent = e.target.parentNode.parentNode;
                                    // console.log(parent);
                                    let category = parent.getAttribute("data-value");
                                    // console.log(category);
                                    $.ajax({
                                        url:"load_dataram.php",
                                        method:"POST",
                                        data:{id:id},
                                        success:function(data){
                                            // console.log(data);
                                            let unitPrice = parent.querySelector("input.unit-price");
                                            // console.log(unitPrice);
                                            unitPrice.value = data;
                                            $(parent).attr("data-id", id);
                                            $(parent).attr("data-quantity", 1);
                                            parent.querySelector("input.quantity").value = 1;
                                            parent.querySelector("input.total-price").value = +data * 1;
                                            grandtotal();
                                        }
                                    });
                                    }
            $("#rams").change(function(){
                var ramid = $("#rams").val();
                // console.log(ramid);
            })


$("#processor").change(function(){
                var pid = $("#processor").val();
                $.ajax({
                    url: 'data.php',
                    method: 'post',
                    data: 'pid=' + pid
                }).done(function(data) {
                    // console.log(data);
                    $('#rams').empty().append('<option>Select Ram</option>');
                    data = JSON.parse(data);
                    var html = '';
                    data.forEach(function(value) {
                        html += '<option value="' + value.id + '">' + value.product_title + '</option>';
                    })
                    $('#rams').append(html);

                });
            })
            function getPriceRam(e){
                                    e.preventDefault();
                                    grandtotal();
                                    var id = $(e.target).val();
                                    // console.log(id);
                                    let parent = e.target.parentNode.parentNode;
                                    // console.log(parent);
                                    let category = parent.getAttribute("data-value");
                                    // console.log(category);
                                    $.ajax({
                                        url:"load_dataram.php",
                                        method:"POST",
                                        data:{id:id},
                                        success:function(data){
                                            // console.log(id);
                                            let unitPrice = parent.querySelector("input.unit-price");
                                            // console.log(unitPrice);
                                            unitPrice.value = data;
                                            $(parent).attr("data-id", id);
                                            $(parent).attr("data-quantity", 1);
                                            parent.querySelector("input.quantity").value = 1;
                                            parent.querySelector("input.total-price").value = +data * 1;
                                            grandtotal();
                                        }
                                    });
                                    }
            $("#rams").change(function(){
                var ramid = $("#rams").val();
                // console.log(ramid);
            })





// insert into db

function submitQuote(e){
  let username   = document.getElementById("name").value;
  let mobile     = document.getElementById("mobile").value;
  let email      = document.getElementById("email").value;
//   if (name.length < 1 || mobile.length < 1 || email.length < 1 ) {
//         alert('Contact field cannot be empty.');
//         // return false;
//     }
//     if ((name==null || name=="") && (mobile==null || mobile=="") && (email==null || email==""))
//   {
//   alert("Please Fillout all the fields!");
//   return false;
//   }
if (username == "") {
            $("#name").css("border", "2px solid red");
            $("#name").focus();
        }
        if (mobile == "") {
            $("#mobile").css("border", "2px solid red");
            $("#mobile").focus();
        }
        if (email == "") {
            $("#email").css("border", "2px solid red");
            $("#email").focus();
        }
   else{


  let categories = document.querySelectorAll("tr.category"); 
  let name       = document.getElementById("name").value;
  let mobile     = document.getElementById("mobile").value;
  let email      = document.getElementById("email").value;
//   console.log(name);
//   console.log(mobile);
//   console.log(email);
  let items = [];
  // console.log(categories);
  Array.from(categories).forEach(category=>{
    let item = {};
    item.id = + category.getAttribute("data-id");
    item.quantity = + category.getAttribute("data-quantity");
    if(item.id !== 0){
      items.push(item);
    }

  });
  // console.log(items);
  let data = JSON.stringify(items);
  console.log(data);

  $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: { data: data },
        complete:
        function () 
        {
            if(data=='[]')
            {
                alert("Please Select product");
            }
            else 
            {
            window.location.href = "reciept.php?dist=" + data + "&name=" + name + "&mobile=" + mobile + "&email=" + email;
            }
        }

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