首页 > 解决方案 > 使用 jQuery 在同一模式中创建和更新表单

问题描述

我有一个共享相同的模态data-target。如果我单击edit按钮,然后关闭并单击add按钮,模态将显示编辑模态而不是添加模态。如何更改表格?

添加按钮:-

<button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#modal-new-ingredients" onClick=(setRestaurantId({{ $restorant_id }}))>{{ __('Add') }}</button>

编辑按钮:-

<button type="button" class="dropdown-item" data-toggle="modal" data-target="#modal-new-ingredients" onClick=(setIngredientsId({{ $bom->id }}))>Edit</button>

setRestaurantId 功能:-

function setRestaurantId(id){
        $('#res_id').val(id);
        // $('#form')[0].reset();
        // $('#ingredients').trigger('change');
        $('#modal-title-new-ingredients').html("Add Ingredient")
        $('#ingredients').val("");
        $('#consumption').val("");

    }

setIngredientsId 函数:-

function setIngredientsId(id){

        ingredients.forEach(element => {

            if(element.id==id){
                console.log('hello', element.raw_material)
                $('#modal-title-new-ingredients').html("Edit Ingredient")
                $('#bom_id').val(element.id);
                $('#ingredients').val(element.raw_material_id);
                $('#consumption').val(element.quantity);
                $('#ingredients').trigger('change');
            }
        });
    }

HTML:-

<form role="form" method="post" action="{{ route('bom.store', $item->id) }}" enctype="multipart/form-data" id="form">
   @csrf

   <div class="form-group">
      <label class="form-control-label" id="form-ingredients" for="ingredients">{{ __('Ingredients') }}</label>
         <select class="noselecttwo form-control" name="ingredients" id="ingredients" required>
              <option disabled selected value> -- Select a Ingredient -- </option>
              @foreach ($ingredients as $ingredient)
                  <option id="var{{$ingredient->id}}" value="{{$ingredient->id}}">{{ $ingredient->name.' - '. $ingredient->rawMaterialUnit->name}}</option>
              @endforeach
         </select>
    </div>

    <div class="form-group">
      <label class="form-control-label" for="consumption">{{ __('Consumption') }}</label>
      <input type="number" step="any" name="consumption" id="consumption" class="form-control" placeholder="{{ __('Consumption') }}" value="" required>
    </div>

    @include('partials.input',['type'=>"hidden",'name'=>'bom_id','id'=>'bom_id','required'=>false,'placeholder'=>'id'])


    <div class="text-center">
     <button type="submit" class="btn btn-primary my-4">{{ __('Save') }}</button>
    </div>
</form>

如果需要,成分的模态 HTML:-

<div class="modal fade" id="modal-new-ingredients" tabindex="-1" role="dialog" aria-labelledby="modal-form" aria-hidden="true">

标签: javascripthtmljqueryformsmodal-dialog

解决方案


当您的模式关闭时,您可以在 jquery中编写事件,并且在其中您可以清空所有值,即:选择和输入。因此,您的代码将如下所示:

 $("#modal-new-ingredients").on('hidden.bs.modal', function(){
    console.log('modal close...');
    $("#modal-new-ingredients").find("input,select").val("")//empty
  });

推荐阅读