使用ajax根据下拉菜单选择更新文本字段

时间:2019-04-09 15:54:20

标签: php jquery ajax database dropdown

每当选择下拉菜单(产品列表)项时,我都试图更新文本字段(价格)。归档的文本将显示所选项目的价格。我想使用ajax进行此操作,但是我对此仍然陌生。

到目前为止,我的代码:

index.php

<?php
  include 'Connection.php';
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="Style.css">
  <title>Shopping Cart</title>
</head>

<body>
  <div id="mainPadding">
    <h1 class="Shopping Title">The Shopping Items</h1>
    <form class="form-horizontal">
      <fieldset class="border p-2">
        <legend class="w-auto">Contact Details:</legend>
        <div class="form-group">
          <label class="control-label col-sm-2" for="name">Name:</label>
          <div class="col-sm-3">
            <input type="name" required class="form-control" id="name" placeholder="Enter Your Name">
          </div>
        </div>
        <div class="form-group">
          <label class="control-label col-sm-2" for="email">Email:</label>
          <div class="col-sm-3">
            <input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" class="form-control" required id="email" placeholder="e.g. shop@shop.shop">
          </div>
        </div>
      </fieldset>
      <fieldset class="border p-2">
        <legend class="w-auto">Available Items:</legend>
        <div class="form-group">
          <label class="col-lg-3 control-label">Item:</label>
          <div class="col-sm-3">
            <div class="ui-select">
              <select id="ItemListDropDown" class="selectpicker" data-live-search="true">
                <div id="itemList">
                  <?php
                      $sql = "SELECT Product_Name FROM products WHERE Availability = 1";
                      $result = mysqli_query($con, $sql);
                      if (mysqli_num_rows($result) > 0)
                        while ($row = mysqli_fetch_assoc($result))
                          echo "<option>" . $row["Product_Name"] . "</option>";
                    ?>
                </div>
              </select>
            </div>
          </div>
        </div>
        <div class="form-group">
          <label class="control-label col-sm-2" for="price">Price</label>
          <div class="col-sm-3">
            <input type="text" disabled class="form-control" id="priceTxt">
          </div>
        </div>
        <div class="form-group">
          <label class="control-label col-sm-2" for="price">Quantity (between 1 and 5):</label>
          <div class="col-sm-3">
            <input type="number" maxlength="1" min="1" max="5" class="form-control" id="priceTxt">
          </div>
        </div>
        <div class="form-group">
          <label class="col-md-3 control-label"></label>
          <div class="col-md-8">
            <input id="addToCart" type="button" class="btn btn-primary" value="Add to the Cart">
          </div>
        </div>
      </fieldset>
      <fieldset class="border p-2">
        <legend class="w-auto">Invoice Details:</legend>
        <div class="form-group">
          <table class="table table-striped" id="ItemTable">
            <thead>
              <tr>
                <th scope="col">Sr.</th>
                <th scope="col">Item Name</th>
                <th scope="col">Price</th>
                <th scope="col">Count</th>
                <th scope="col">Total</th>
                <th scope="col">Delete</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <th scope="row"></th>
                <td id="ItemName"></td>
                <td id="Price"></td>
                <td id="Count"></td>
                <td id="Total"></td>
                <td id="DeleteButton"></td>
              </tr>
            </tbody>
          </table>
          <div class="form-group">
            <label class="col-md-3 control-label"></label>
            <div class="col-md-8">
              <input id="PrintAndSend" type="submit" class="btn btn-primary" value="Print and Send to Email">
            </div>
          </div>
        </div>
      </fieldset>
    </form>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
  <script src="Javascript.js"></script>
</body>
</html>

Javascrpt.js

$(document).ready(function() {
  $("#ItemListDropDown").change(function() {
    $("#itemList").load("load-product.php")
    // $("#priceTxt").attr("value", price);
  });      
});

load-product.php

  <?php
include 'Connection.php';


$sql = "SELECT Product_Name FROM products WHERE Availability = 1";

$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
    while ($row = mysqli_fetch_assoc($result))
        echo "<option>" . $row["Product_Name"] . "</option>";
?>

我正在尝试使用Ajax做一些事情,解决该问题将使我为剩下的一切做好准备。

1 个答案:

答案 0 :(得分:1)

蛇,您不需要Ajax就能获得产品价格,而只需使用data-*属性:

在您的php中(不是load-product.php文件):

<?php
$sql = "SELECT Product_id, Product_Name, Product_price FROM products WHERE Availability = 1";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
echo "<option value='default' data-price='default'>Choose a item </option>";
while ($row = mysqli_fetch_assoc($result))
echo "<option value='{$row["Product_id"}' data-price='{$row["Product_price"]}'>" . $row["Product_Name"] . "</option>";
?>

然后在您的JavaScript中执行此操作以获取商品价格:

// JavaScript using jQuery
$(function(){
    $('#ItemListDropDown').change(function(){
       var selected = $(this).find('option:selected');
       var extra = selected.data('price'); 
       $("#priceTxt").val(extra); // set your input price with jquery
       $("#priceTxt").prop('disabled',false);//set the disabled to false maybe you want to edit the price
       ...
    });
});

// Plain old JavaScript
var sel = document.getElementById('ItemListDropDown');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-price');
var priceInput = document.getElementById('priceTxt');
priceInput.disabled = false;
priceInput.value =extra;

希望对您有帮助=)