Search code examples
javascriptphpcodeigniterautofill

How can i make auto fill an input form based on selectbox dropdown?


I'm trying to auto fill an input form based on the selection of a selectbox. the auto fill text comes from my database

This is my code:

<select style="width: 110px;" class="form-control" name="id_periodik" id="id_periodik" required oninvalid="this.setCustomValidity('Masukkan periodik sparepart!')"
oninput="this.setCustomValidity('')">
<?php foreach ($periodik_options as $option) {?>
<option value="<?php echo $option['id_periodik']; ?>">
<?php echo $option['nama_periodik']; ?>
</option>
<?php }?>
</select>
</td>

text auto fill based on selection:

<td>
<input type="text" class="form-control" id="jumlah_periodik" name="jumlah_periodik[]" readonly>
</td>

script:

<script>
$(document).ready(function() {
$('#id_periodik').on('change', function() {
var selectedValue = $(this).val();
$('#jumlah_periodik').val(selectedValue);
});
});
</script>

i've try that but nothing happens in my view. Any help you can give I appreciate it enter image description here


Solution

  • $(document).ready(function() {
        $('#id_periodik').on('change', function() {
            // here is the change
            var selectedValue = $('#id_periodik').find(":selected").val();
    
            $.ajax({
                    type : "Get",
                    url: 'your_url',
                    data: {id_periodik: selectedValue},
                    success:function(result){
                        $('#jumlah_periodik').val(result);
                    }
                });
        });
    });
    
    1. Get selected id_periodik 2. Then send ajax request to get data from database 3. Then set data to jumlah_periodik Hope this work