1

I have html <select> element that is populated by data in database using javascript append. I wanted to make distinction by applying style="color:red" for values that have payment_status = false and style="color:green" for values that have payment_status = true. How would I be able to insert style on it. I tried to insert style but the values won't show up in the dropdownlist. Please help me figure this out. Please take a look at the code below. Thank you.

$('#schedule_payment').append($('<option>', {
    value: '',
    text: 'Select Schedule'
}));

$.each(obj.amortizations, function(i, item) {
    if (item.payment_status == true) {
        $('#schedule_payment').append($('<option style="color:red">', {
            value: item.schedule,
            text: item.schedule
        }));
    } else {
        $('#schedule_payment').append($('<option>', {
            value: item.schedule,
            text: item.schedule
        }));
    }
});

enter image description here

golddragon007
  • 1,247
  • 14
  • 27
Eli
  • 1,256
  • 4
  • 29
  • 59
  • Possible duplicate of [How to style the option of an html "select" element?](https://stackoverflow.com/questions/7208786/how-to-style-the-option-of-an-html-select-element) – Carsten Løvbo Andersen Apr 03 '19 at 09:24

1 Answers1

1

I think this is your solution:

var obj = {amortizations: [{
  payment_status: true,
  schedule: 1000
},{
  payment_status: false,
  schedule: 10000
},{
  payment_status: false,
  schedule: 20000
},{
  payment_status: true,
  schedule: 100000
}]};

$('#schedule_payment').append($('<option>', { 
  value: '',
  text : 'Select Schedule'
}));
  
$.each(obj.amortizations, function (i, item) {
  if( item.payment_status == true ){
    $('#schedule_payment').append($('<option style="color:red">').attr('value', item.schedule).text(item.schedule));
  }else{
    $('#schedule_payment').append($('<option style="color:green;">').attr('value', item.schedule).text(item.schedule));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="schedule_payment"></select>

or:

var obj = {amortizations: [{
  payment_status: true,
  schedule: 1000
},{
  payment_status: false,
  schedule: 10000
},{
  payment_status: false,
  schedule: 20000
},{
  payment_status: true,
  schedule: 100000
}]};

$('#schedule_payment').append($('<option>', { 
  value: '',
  text : 'Select Schedule'
}));
$.each(obj.amortizations, function (i, item) {
  if( item.payment_status == true ){
    $('#schedule_payment').append($('<option>', {
      style: 'color:red',
      value: item.schedule,
      text: item.schedule
    }));
  }else{
    $('#schedule_payment').append($('<option>', {
      style: 'color:green',
      value: item.schedule,
      text: item.schedule
    }));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="schedule_payment"></select>
golddragon007
  • 1,247
  • 14
  • 27