Button Press
Button Press

Reputation: 641

Laravel CRUD Ajax Edit: show selected value from table on dropdown

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.

Upvotes: 0

Views: 941

Answers (1)

Alex T
Alex T

Reputation: 84

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();
    

Upvotes: 1

Related Questions