-3

i have this select option

<select class="form-select" aria-label="select-kondisi">
 <option selected>Kondisi</option>
 <option value="baik">Baik</option>
 <option value="rusak">Rusak</option>
</select>

and here is my ajax

$.ajax(
 {
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  },
  url: '/databarang/getubah',
  data: {id_barang : id_barang},
  method: 'post',
  dataType: 'json',
  success: function(data){
    $('#kondisi').val(data.kondisi);
  }
 });

what i want is how to auto choose option from ajax with value from var data, thank you very much

  • 2
    Approach appears ok but the select does not have the id shown in the jQuery selector. Also not clear what the response data structure is nd if the success callback is firing – charlietfl Nov 25 '21 at 23:43
  • This doesn't seem to be a problem with specifying the value of an HTML element as an ajax return value. Basically, it seems that you don't know how to auto-set the value of the select box. Maybe this will help. https://stackoverflow.com/questions/78932/how-do-i-programmatically-set-the-value-of-a-select-box-element-using-javascript – Web Star Nov 26 '21 at 00:18

2 Answers2

0

Is this what you mean? You can just set the value of the select menu: ie: $('select.form-select').val('baik')

$(document).ready(function() {
  setTimeout(() => {
    $('select.form-select').val('baik');
  }, 1000)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-select" aria-label="select-kondisi">
  <option selected>Kondisi</option>
  <option value="baik">Baik</option>
  <option value="rusak">Rusak</option>
</select>
Kinglish
  • 23,358
  • 3
  • 22
  • 43
0

there is no id named "kondisi", but you are using "kondisi" as id.

$('#kondisi').val(data.kondisi);

define id as below

<select class="form-select" id="kondisi" aria-label="select-kondisi">
 <option selected>Kondisi</option>
 <option value="baik">Baik</option>
 <option value="rusak">Rusak</option>
</select>