0

Controller:

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

Ajax:

$('#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);

Form:

<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>

my current code outputs school_name and school_description without any issue, but how do I do the same in a dropdown? for instance, the options are "Math" and "Science", in the table data, "Science" is chosen and I need the first option to show in my edit as "Science".

So basically, if "Science" is chosen, it will look something like:

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

normally, in the add form, there are only two options, Math and Science. The edit form will have three, the first option in the edit will always be the selected one from the database.

I know i cannot simply do:

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

Because the option content will be empty.

Any help would be appreciated.

Button Press
  • 623
  • 6
  • 26
  • Does the subject has an ID or slug? If not, you can convert the name into a slug, then pass that as the value of option, then you can compare to check what was selected in the dropdown – Héctor William Jun 27 '21 at 21:15

1 Answers1

1

Referencing https://stackoverflow.com/a/16979926/7970660:

  1. Assign a value to your options.

    For Example:

    <select id="edit_subject_name">
       <option value="Math">Math</option>
       <option value="Science">Science</option>
    </select>
    
  2. In your AJAX:

    $("#edit_subject_name").val(response.school_edit.subject_name).change();
    
Alex T
  • 84
  • 1
  • 6