php - 通过Ajax价格数据来形成输入文本,而不是选择产品的价格,而是总是带第一个价格
问题描述
我准备了一个销售记录表,您首先选择产品/库存名称。一旦做出此选择,它应该使用应该从数据库中的库存表中获取的该产品/股票的价格填充下面名为 unit_sales price 的字段。发生这种情况的部分原因是第一个库存/产品的价格被获取并且只出现在浏览器控制台中。帮助我获取特定产品的价格,并使其不仅出现在控制台中。我附上了一张数据库图片。
创建.blade.php
@extends('layouts.app')
@section('content')
<br>
<h1>Add Sale</h1>
{!! Form::open(['action' => 'SalesController@store', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
<div class="form-group">
<label >Product Name</label>
<select name="product_name" class="form-control" id="stock_name">
<option>Select Product Name</option>
@foreach ($stocks as $stock)
<option value="{{ $stock->stock_name }}" >{{ $stock->stock_name}}</option>
@endforeach
</select>
</div>
<script>
$(document).ready(function() {
$("#stock_name").on('change', function () {
let element = $(this);
$.ajax({
url: '/sales-price/getunitsellingprice',
method: 'GET',
data: {
'stock_name' : element.val(),
},
success: function (response) {
$("#unit_selling_price").val(response);
},
});
});
});
</script>
<div class="form-group">
{{Form::label('unit_selling_price', 'Unit Selling Price')}}
{{Form::text('unit_selling_price', '', ['class' => 'form-control', 'placeholder' => 'Unit Selling Price', 'id' => 'unit_selling_price'])}}
</div>
@endsection
销售控制器.php
public function getUnitSellingPrice(Request $request)
{
$stock_name = $request->input("stock_name");
if($stock_name = null){
return null;
}
$stock = Stock::where('stock_name', 'like', "%".$stock_name."%")->first();
if ($stock == null) {
return null;
}
return response()->json($stock->unit_selling_price);
}
DB截图:股票表
https://slack-files.com/TP02E38GN-FP2G2BM2S-5cb95174a0
表格截图
解决方案
您可以在此处省略触发器。并像这样重写这一行
$("#unit_selling_price").val(response.data);
还要获得您必须使用的选定选项值
let element = $(this+' :selected');
推荐阅读
- .net - 连接到 IIS 并找到 .NET DLL
- python - Python多线程正在django中混合不同请求的数据
- algorithm - 这段代码的时间复杂度是多少?
- django - 已解决:Django - WSGI 脚本无法作为 Python 模块加载
- sql - PostgreSQL 不会删除重复项
- c++ - C++ 等价于 Java 的匿名类
- python - 我试图找到一种方法来完成这项工作,它试图计算一个短语在逐行文本文件中出现的次数
- javascript - 在连接时更新 Firebase 中的用户配置文件
- jmeter - 如何在 JMeter 5.2.1 中参数化线程数
- julia - julia:如何读取 bz2 压缩文本文件