首页 > 解决方案 > Laravel CRUD Ajax 编辑:在下拉列表中显示选定的值

问题描述

控制器:

$school_edit = SchoolData::find($school_id);

阿贾克斯:

$('#edit_school_name').val(response.school_edit.school_name);                      
$('#edit_school_description').val(response.school_edit.school_description);
$('#edit_cat_id').val(response.school_edit.school_id);
$('#edit_subject_name').val(response.school_edit.subject_name);

形式:

<input type="text" id="edit_school_name" class="form-control form-group w-100" placeholder="School Name">
<textarea id="edit_school_description" class="form-control w-100" placeholder="School Description" cols="50" rows="10"></textarea>

我当前的代码输出 school_name 和 school_description 没有任何问题,但我如何在下拉列表中做同样的事情?例如,选项是“数学”和“科学”,在表格数据中,选择了“科学”,我需要第一个选项在我的编辑中显示为“科学”。

所以基本上,如果选择“科学”,它看起来像:

  <select id="edit_subject_name">
    <option>(selected subject from database)</option>
    <option>Math</option>
    <option>Science</option>
  </select>

通常,在添加表单中,只有两个选项,数学和科学。编辑表单将有三个,编辑中的第一个选项将始终是从数据库中选择的一个。

我知道我不能简单地做:

<option id="edit_subject_name"></option>
<option>Math</option>
<option>Science</option>

因为选项内容将为空。

任何帮助,将不胜感激。

标签: ajaxlaravelhtml-selectcrudedit

解决方案


参考https://stackoverflow.com/a/16979926/7970660

  1. 为您的选项分配一个值。

    例如:

    <select id="edit_subject_name">
       <option value="Math">Math</option>
       <option value="Science">Science</option>
    </select>
    
  2. 在您的 AJAX 中:

    $("#edit_subject_name").val(response.school_edit.subject_name).change();
    

推荐阅读