简体   繁体   English

根据第一个选择框显示产品数量

[英]Display the amount of the product based on the first select box

I have trouble displaying the amount of a product based on what i picked on the initial select box.我无法根据我在初始选择框中选择的内容显示产品数量。 I have only 1 table named products and it contains the columns id, name, amount.我只有 1 个名为 products 的表,它包含列 id、name、amount。

product.blade.php产品.blade.php

<td>
 <select name="product">
    <option selected="true" disabled="true">Products</option>
     @foreach($products as $id => $p)
        <option value="{!!$id!!}">{!!$p!!}</option>
     @endforeach
 </select>
</td>
<td>
    <input id="amount" type="text" name="amount" class="form-control 
    required" value=""/>
</td>

javascript javascript

 $('#product').on('change', function () {
        var productid=$(this).val();
        var a=$(this).parent();
        var op="";
        $.ajax({
            type:'get',
            url:'{!!URL::route('getAmount')!!}',
            data:{'id':productid},
            dataType:'json',
            success:function(data){
                console.log(data.amount);
                a.find('#amount').val(data.amount);
            },
            error:function(){
            }
        });
    });

Controller控制器

public function getProducts()
{
  $products = Product::lists('name', 'id', 'amount');
  return view('product', compact('products');
}

public function getAmount(Request $request){

  $product=Product::select('amount')->where('id',$request->id)->first();

  return response()->json($product);
}

Routes路线

Route::get('product', ['as' => 'product',
        'uses' => 'ProductController@getProducts']);
Route::get('/product/getAmount', ['as' => 'getAmount',
        'uses' => 'ProductController@getAmount']);

I just want to display the amount of the product on the input box next to it.我只想在旁边的输入框中显示产品的数量。

Doing an ajax request seems quite useless to me wouldn't it be easier to just add a data attribute to the option.执行 ajax 请求对我来说似乎毫无用处,只是向选项添加数据属性不是更容易吗。

<td>
    <select id="products" name="product">
        <option selected="true" disabled="true">Products</option>
        @foreach($products as $id => $p)
            <option data-amount="{{ $p->amount }}" value="{{ $id }}">{{ $p }}</option>
        @endforeach
     </select>
</td>
<td>
    <input id="amount" type="text" name="amount" class="form-control required" value=""/>
</td>

And then add some javascript or jquery to fill the input when the select is changed.然后在选择更改时添加一些 javascript 或 jquery 来填充输入。

$("#products").change(function() {
    $("#amount").val($("#products option:selected").data("amount"))
})

Also, watch out where you are using {!!另外,请注意您在何处使用 {!! !!} cause you might be introducing XSS which you definitely don't want. !!} 因为你可能会引入你绝对不想要的 XSS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM