How to remove duplicate option from Select dropdown using JQuery

How to remove duplicate option from Select dropdown using JQuery

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Codelizar - Remove duplicate options</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
   <h1>Method 1</h1>
   <select id="sel_box">
    <option value="">All Equipment</option>
    <option value="1">Dumbells</option>
    <option value="2">Plates</option>
    <option value="3">Rodes</option>
    <option value="4">Benches</option>
  </select> 
  
  <h1>Method 2</h1>
  <select id="sel_box_another">
    <option value="">All Equipment</option>
    <option value="1">Dumbells</option>
    <option value="2">Plates</option>
    <option value="3">Rodes</option>
    <option value="4">Benches</option>
  </select> 
 </body>

 <footer>
     <script type="text/javascript">
        $(document).ready(function(){
           /* js for method - 1 */
           var map = {};
           $('#sel_box').each(function () {
             if (map[this.value]) {
               $(this).remove()
             }
             map[this.value] = true;
           });
           
           /* js for method - 2 */ 
           $("#sel_box_another").val(function(idt, val) {
              $(this).siblings('[value="'+ val +'"]').remove();
           });
        });
     </script>
 </footer>
</html>


 

Leave a Reply

Your email address will not be published. Required fields are marked *