How to reset select when a particular option is selected

Viewed 82

I want to create a dummy option which is just used to trigger a modal , I don't want that option to be selected

Here is Html:

  <select  onchange="setCookie('addcategory', this.value, 365);">
    <option hidden disabled selected value> -- select a category -- </option>
      <?php foreach( $categories as $index => $category ) :?>
    <option value="<?php echo $category ?>" ><?php echo $category ?></option>
      <?php endforeach ?>
    <option value="I_C_M">+++++++Click to Add new+++++++</option>
  </select>

Here is what I have tried:

$('select').on('change', function() {
  if(this.value === "I_C_M"){
    $(this.parentNode).prop('selectedIndex',-1);
    $('#insert_category_modal').modal('show');
  }
});

"Click to add new" is the dummy option

1 Answers

I think you should set the selectedIndex to 0 on the current element using this object.

Demo:

$('select').on('change', function() {
  if(this.value === "I_C_M"){
    $(this).prop('selectedIndex', 0);
    //$('#insert_category_modal').modal('show');
  }
});

function setCookie(c, v, d){}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select  onchange="setCookie('addcategory', this.value, 365);">
  <option hidden disabled selected value> -- select a category -- </option>

  <option value="test" >Test</option>

  <option value="I_C_M">+++++++Click to Add new+++++++</option>
</select>

Related