Skip to content
Advertisement

Display option data with php and hide the similiar

I’m using php to select data from my database. I’m displaying it in a HTML select option tag. I have 100+ options and I want to hide which is the same as my selected data. For example:

<select class="form-control" id="type" name="type" required>
    <option selected value='<?php echo $type; ?>'><?php echo $type; ?></option> // for example $type == "c"
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
    <option value="d">d</option>
</select>

For example the $type variable is “c”. So it displays the option “c” twice. How can I easily hide always the one that I need if I have 100+ option values?

Advertisement

Answer

Manually remove all duplicate option tags with JavaScript and jQuery

let values = []
$("option").each((index, item) => {
  let { value } = item //item.value is the value of our current option in the loop
  
  // check if value is already in values array
  if(values.includes(value)) {
    // delete duplicate from the DOM
    item.remove()
  } else {
    // push value to values array so that duplicates can be detected later on
    values.push(value)
  }
})

console.log(values)
<select class="form-control" id="type" name="type" required>
    <option selected value="c">c</option>
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
    <option value="d">d</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Alternative solution

If your given options a, b, c, d are always the same you could setup a „blacklist“ in your PHP code and only echo out the html option element if it‘s not in this blacklist. Is this a possible solution for you?

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement