在下拉菜单中选择时自动填充输入字段

问题描述 投票:0回答:1

我是 Laravel 新手。当选择立法者的特定名称时,我尝试在输入字段上自动显示分配值,但是,我只得到分配:null。请帮助我。

我创建分配表

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up()
    {

        // Drop the table if it exists
        Schema::dropIfExists('allocations');


        Schema::create('allocations', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('name_of_legislator_id');
            $table->bigInteger('allocation');
            $table->foreign('name_of_legislator_id')->references('id')->on('name_of_legislators');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('allocations');
    }
};

我的分配模型

class Allocation extends Model
{
    use HasFactory;

    protected $table = 'allocations';

    protected $fillable = [
        'name_of_legislator_id',
        'allocation'
    ];

    public function nameOfLegislator()
    {
        return $this->belongsTo(NameOfLegislator::class, 'name_of_legislator_id', 'id');
    }
}

**我的控制器**

  public function getAllocations(Request $request)
  {
    $legislatorID = $request->name_of_legislator_id;

    if ($request->ajax()) {
      $allocation = Allocation::where('name_of_legislator_id', $legislatorID)->value('allocation');
      return response()->json(['allocation' => $allocation]);
    }
  }

我的jquery和html

            $(document).on("change", ".legislator", function(e) {
                e.preventDefault();

                let legislatorID = $(this).val();

                $.ajax({
                    type: "POST",
                    url: "{{ route('targets.get-allocations') }}",
                    data: {
                        name_of_legislator_id: legislatorID
                    },
                    success: function(response) {
                        let allocationInput = $(".allocation");

                        if (response && response.allocation !== null) {
                            allocationInput.val(response.allocation);
                        } else {
                            allocationInput.val('');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log(xhr.responseText);
                    }
                });
            });
     <td>
    <input type="number" name="allocation" class="form-control allocation"                placeholder="Allocation" required min="0" readonly>
    </td>

我想要的是,当在下拉列表中选择立法者姓名的特定名称时,分配给他们的分配值将自动显示在输入字段中。

php html jquery ajax laravel
1个回答
0
投票

在控制器查询中获取立法者所有分配的总和

$allocation = Allocation::where('name_of_legislator_id', $legislatorID)->sum('allocation');

或获取最新分配

$allocation = Allocation::where('name_of_legislator_id', $legislatorID)->latest()->value('allocation');

但是我注意到你提到你正在获得分配:null 这可能是由于一些常见原因

请检查数据库记录例如 在您的分配表中,并且 name_of_legislator_id 值与您的 name_of_legislators 表中的 id 值正确对应。如果没有匹配的记录,查询将返回null。 (这可能是原因之一)

其次请在 jquery Ajax 请求中查找 CSRF 令牌 https://laravel.com/docs/10.x/csrf

<script>
$(document).ready(function() {
    $(document).on("change", ".legislator", function(e) {
        e.preventDefault();
        let legislatorID = $(this).val();

        $.ajax({
            type: "POST",
            url: "{{ route('targets.get-allocations') }}",
            data: {
                _token: "{{ csrf_token() }}", // Include CSRF token for Laravel
                name_of_legislator_id: legislatorID
            },
            success: function(response) {
                let allocationInput = $(".allocation");
                if (response && response.allocation !== null) {
                    allocationInput.val(response.allocation);
                } else {
                    allocationInput.val('');
                }
            },
            error: function(xhr, status, error) {
                console.log(xhr.responseText);
            }
        });
    });
});
</script>

您的控制器

public function getAllocations(Request $request) {
    if ($request->ajax()) {
        $legislatorID = $request->name_of_legislator_id;
        $allocation = Allocation::where('name_of_legislator_id', $legislatorID)->value('allocation');
        return response()->json(['allocation' => $allocation]);
    }
}

我希望这有帮助

如果可能,请分享代码仓库

© www.soinside.com 2019 - 2024. All rights reserved.