JSFiddle - React, Tailwind, and code Playground

by jabrane jabri

HTML

<select>
    <option value></option>
    <option value="V: Volvo">Volvo</option>
    <option value="S: Saab">Saab</option>
    <option value="O: Opel">Opel</option>
    <option value="A: Audi">Audi</option>
</select>

JavaScript

$(document).ready(function(){
var previous;

    $("select").on('focus', function () {
        // Store the current value on focus and on change
        previous = this.value;
    }).change(function() {
        // Do something with the previous value after the change
        if(this.value!=="" && this.value!==previous  && previous!==""){
        $("select option[value='"+previous+"']").remove();
        var newVal = $(this).val().split(':')[0];
          $(this).append($('<option>', {
            value: newVal,
            text: newVal
          }));
			$(this).val(newVal);
      $(this).find('option:selected').hide();

        }
        else if(previous=="" && this.value!=""){
        var newVal = $(this).val().split(':')[0];
          $(this).append($('<option>', {
            value: newVal,
            text: newVal
          }));
			   $(this).val(newVal);
         $(this).find('option:selected').hide();
        }
        else if(previous!="" && this.value==""){
         $("select option[value='"+previous+"']").remove();
        }
        previous = this.value;
    });
  });