Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
55 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...