Search code examples
codeigniterdropdown

How to display div when a specific select option is selected from the database in CodeIgniter


I am stuck here. I am trying to display a div if only a specific select option is selected from the database (CodeIgniter), here is my code.

Option Box: (Quick Loan, Pawn)


<div class="mb-3 col-md-6">
<label class="form-label">Loan Type <span class="text-danger">*</span></label>
<select class="default-select form-control wide" name="loan_type" id="loan_type" required>
<option value="" selected>-- Select Type --</option><?php foreach ($loan_types as $loan_type) : ?><option value="<?= $loan_type->loan_reference ?>"><?= $loan_type->loan_title ?></option>
<?php endforeach; ?></select>
</div>

Div to show if pawn is selected:

<div class="mb-3 col-md-6" id="collateral">
<label class="form-label">Collateral Image (Pawn Loan) </label>
<input type="file" class="form-control-file" name="collateral_image"  id="ci">
</div>

JavaScript

$(document).ready(function(){
   $('#collateral').hide();
   $("#loan_type").change(function(){

     $('#collateral').hide();
     $('#ci').prop('required', false);
     
     $('option:selected', this).each(function(i,sel){     
       if ($(sel).val() == 'Pawn') {
         $('#collateral').show();
         $('#ci').prop('required', true);
       }
     });
 });
});

Solution

  • The HTML and JavaScript code that you have posted looks correct, so maybe it is the data that does not match up. My guess is that loan_reference is something else such as lowercase "pawn" or an id. Check if the value of $loan_type->loan_reference is in fact "Pawn", by adding this line before your if line:

    console.log('value of selected option:', $(sel).val());
    

    My guess is that loan_reference is something else such as lowercase "pawn" or an id.

    Other than that, it looks like you are using jQuery, so confirm that jQuery is actually there:

    console.log($(). jquery);