Shibbir
Shibbir

Reputation: 2031

How to hide selected option from list

I have following HTMLselect fields:

<select name="title_42434" class="anyform-control form_select_tag"> 
  <option value="h1">h1</option> 
  <option value="h2">h2</option> 
  <option value="h3">h3</option> 
  <option value="h4">h4</option> 
  <option value="h5">h5</option> 
  <option value="h6">h6</option> 
</select>

Now, Using jQuery I am adding selected attribute when I choose any one of them.

for e.g;

I choose h2. jQuery will add selected attribute.
again, I choose h3. jQuery will add selected attribute.

But

I want it should be selected only one option. Means the last selected option will be removed.

jQuery selected code:

$(document).on('change', '.form_select_tag', function () {
  var op_val = $(this).val();    
  var field = $(this).closest('.row').attr('data-field');    
  $(this).find('option[value=' + op_val + ']').attr("selected", "selected");    

  //any other code to remove last selected option ?? 

  getPreview();
});

Upvotes: 1

Views: 39

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206008

CSS - Hide selected option

In pure CSS you could use the option:checked pseudo

option:checked {
  display: none;
}
<select name="title_42434" class="anyform-control form_select_tag">
  <option selected disabled>Select Heading</option>
  <option value="h1">h1</option>
  <option value="h2">h2</option>
  <option value="h3">h3</option>
  <option value="h4">h4</option>
  <option value="h5">h5</option>
  <option value="h6">h6</option>
</select>

jQuery - Hide selected option

To make hidden the currently selected <option>

$(document).on('change', '.form_select_tag', function() {
  $(this).find('option').prop('hidden', i => this.selectedIndex == i);
});
<select name="title_42434" class="anyform-control form_select_tag">
  <option selected disabled>Select Heading</option>
  <option value="h1">h1</option>
  <option value="h2">h2</option>
  <option value="h3">h3</option>
  <option value="h4">h4</option>
  <option value="h5">h5</option>
  <option value="h6">h6</option>
</select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 2

Related Questions