0

I want to get data from database and show it to edit form. When I'm using json data, I've got problem on show the data to select option field form. It still show option value id ascending , not show value id selected from database.

In the example, I need to change lesson with id number 7. And in the select option, it shows lesson from id number 1, but when I click the select option, it shows id with number 7.

Here's the jquery code

function edit(id){

    $.ajax({
        url : url + 'Lesson/find_by_id',
        type: 'POST',
        data: {id: id},
        success: function(response){
             var jsonData = JSON.parse(response);

             $('input[name="id"]').val(jsonData.id);
            
             $('select[name="lesson"]').val(jsonData.lesson_id);
             $('textarea[name="description"]').val(jsonData.description);

             
        }
    });

    $('#editModal').modal('show');
}

Here's the form code

 <select class="form-control select-search" name="lesson" style="width: 100%" required="">
    <?php foreach($lesson as $row): ?>
            <option value="<?=$row->lesson_id?>" > <?=strtoupper($row->name)?> </option>
    <?php endforeach; ?>
</select>

Here's the controller code

public function find_by_id(){
    $lesson_id = $this->input->post('id');
    $data     = $this->lesson->find_lesson($lesson_id);

    echo json_encode($data);
}

Do you know how to fix the code ?

Thank you

Ikram Shabri
  • 557
  • 1
  • 7
  • 19
  • If you're seeing that behaviour it means that the value of `jsonData.lesson_id` does not match any `value` attribute in an `option` within the target select. We can't offer any more help than that at this point – Rory McCrossan Dec 14 '20 at 08:57
  • Hi @RoryMcCrossan, so why when we click the `select option` arrow, then it shows `value selected` ? – Ikram Shabri Dec 14 '20 at 09:00
  • It is hard to understand your question, but I think you are saying that your Javascript *does* select the right option, but the dropdown is not updated to show that? – Don't Panic Dec 14 '20 at 09:04
  • Hi @Don'tPanic, yes it is – Ikram Shabri Dec 14 '20 at 09:08
  • I think you are saying that your Javascript does select the right option, but the dropdown is not updated to show that?. use this after setting value of dropdown $('.check').trigger('change'); – Hammad Ahmed khan Dec 14 '20 at 09:09
  • https://stackoverflow.com/a/33252307/6089612 – Don't Panic Dec 14 '20 at 09:11
  • Does this answer your question? [Set select option 'selected', by value](https://stackoverflow.com/questions/13343566/set-select-option-selected-by-value) – Don't Panic Dec 14 '20 at 09:12

0 Answers0