Matt Cooper
Matt Cooper

Reputation: 3

Hide Option within Select box using Jquery / Javascript

I'm looking to hide just one option within a select box using Jquery/Javascript. I've tried CSS to display: none but it doesn't work on all browsers and I can't edit the option directly to add "hidden" or similar.

https://impactdigitaldev.co.uk/bookly/

In the first drop-down "category" I'm trying to hide the "lane hire" option. Which you can see has a value="5" so I've tried the following script but it's not working if you have any suggestions I'd be really grateful.

$("#cats option[value='5']").remove();

I also tried without the ID and still no luck

$("option[value='5']").remove();

Upvotes: 0

Views: 101

Answers (3)

Moose
Moose

Reputation: 84

$("#cats option[value='5']").remove();

Does work, you've got an uncaught type error in your console though which probably is why the script doesn't run.

As you can see in the screenshot below I ran your snippet in the browser console, resulting in a removed option.

enter image description here

In case you are interested, this can be easily handled through regular javascript as such:

document.querySelector("#cats option[value='5']").remove();
<div class="bookly-form-group" id="cats" data-type="category">
<label>Category</label> 
  <div>
    <select>
      <option value="0">Category</option>
      <option value="1">coaching</option>
      <option value="5">lane hire</option>
    </select>
  </div> 
</div>

Upvotes: 0

hermes14
hermes14

Reputation: 11

$("select option[value='5']").remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="0">Category</option>
   <option value="1">coaching</option>
   <option value="5">lane hire</option>
</select>

Working fiddle https://codepen.io/hermes14/pen/VwyrXjr?editors=1111

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 77083

You don't need to escape the block quote:

document.querySelector("option[value='5']").remove();
<select>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
<select>

Upvotes: 0

Related Questions