【问题标题】:Laravel, jquery - Fill input box as per select boxLaravel,jquery - 根据选择框填充输入框
【发布时间】:2017-12-09 06:34:26
【问题描述】:

我正在使用 jQuery 构建一个 Laravel 应用程序。我有一个带有选择框(产品列表)和文本输入字段的表单。

我的要求是当我从顶部的选择框中选择产品时,所有其他字段的值应根据从数据库中为所选产品获取的产品值进行更新。

这是我的 js 脚本:

$(document).ready(function() {

    var divKey = $( "#proposed_product option:selected" ).val();

    $( "#proposed_product" ).change(function() {
        updateKeyValues();
    });

    function updateKeyValues() {
        $("#proposed_product").val(divKey);
        console.log(proposed_product); //what to do here..???

    }

});

我的 laravel 函数返回演出列表:

public function proposegigs($id){
    $gig = Gig::findOrFail($id);
    return $gig;

有人可以帮助如何实现这一目标吗?

【问题讨论】:

  • 进行一些 ajax 调用,否则客户端 js 无法弄清楚如何处理服务器端数据
  • 要求是从数据库中获取所选产品的详细信息,如标题、描述、价格等,并用这些数据填充其他字段。

标签: javascript php jquery laravel


【解决方案1】:

调用ajax获取数据

$( "#proposed_product" ).change(function() {
    $.ajaxSetup({
       headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
       url: "{{ route('your-route') }}",
       type: "POST",
       data: {id: $( "#proposed_product :selected" ).val()}, //send data to controller
       success: function(result){
           console.log(result);
           //check the console then put the data where you want
       }
    });

    $.ajax();
});

在您的控制器中返回 json 响应

public function proposegigs(Request $request){
    $gig = Gig::findOrFail($request->id);
    return response()->json(['data' => $gig]);
}

【讨论】:

    【解决方案2】:

    您可以禁用未更改的项目,如下所示,

    $( "#proposed_product" ).change(function() {
    
        var selectedItem = $(this)
    
        $.each( $( "#proposed_product" ).children('option'), function (index, item) { 
            if(selectedItem.val() != $(item).val()) {
                $(this).prop('disabled', true)
            }
        })
    });
    

    此外,您可以根据您发送的请求结果的数据更改选项项目。

    $( "#proposed_product" ).change(function() {
    
        var selectedItem = $(this)
    
        // Example Request
        $.get('https://httpbin.org/get', function(data) {
            $.each( $( "#proposed_product" ).children('option'), function (index, item) { 
                if(selectedItem.val() != $(item).val()) {
                    $(this).text(data.origin)
                }
            })
        })
    });
    

    另外,你的回复必须是json格式,

    public function proposegigs(Request $request){
        $gig = Gig::findOrFail($request->id);
        return response()->json($gig, 200);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多