Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
53 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65642295/display-option-data-with-php-and-hide-the-similiar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...