首页 > 解决方案 > 使用ajax根据下拉菜单选择更新文本字段

问题描述

I'm trying to update a text field (Price) whenever a drop-down menu (List of Products) item is selected. 提交的文本将显示所选项目的价格。我想使用 ajax 来做到这一点,但我还是新手。

到目前为止我的代码:

索引.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);
  });      
});

加载产品.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 做一些事情,解决这个问题将使我为其余的事情做好准备。

标签: phpjqueryajaxdatabasedropdown

解决方案


Snake,您不需要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;

希望它有帮助=)


推荐阅读