0

I'm building a select dropdown, with the following function:

        $.each(data,function(key, value) {
            $select.append('<option value=' + key + '>' + value + '</option>');
        });

Here I copy a sample of my origin data:

231:"Building"
232:"Trusting"
234:"Engineering"
235:"(*)Monitoring"
236:"Managing"

When building it, I want to:

  1. Mark the option that begins with '(*)' as selected, so I need to conditionally add the attr 'selected' to the option.
  2. Remove the '(*)' from the value shown.

Thanks for your help!

Capiedge
  • 226
  • 3
  • 10

1 Answers1

0

You can use .find to figure out if the string starts with '(*)' then add selected to the end of the option and use slice to remove the '(*)'.

data = {
  231:"Building",
  232:"Trusting",
  234:"Engineering",
  235:"(*)Monitoring",
  236:"Managing"
}
$select = $("#select");
from = '(*)';
$.each(data,function(key, value) {
  if (value.indexOf(from) == 0) {
    $select.append('<option value=' + key + ' selected>' + value.slice(from.length) + '</option>');
  } else {
    $select.append('<option value=' + key + '>' + value + '</option>');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select"></select>
Neil
  • 14,063
  • 3
  • 30
  • 51