skip to Main Content

My list can not have an option value like

<option value="some_value"> Some text</option>

My current code is

<select id="select1">   
     <option>One</option>   
     <option>Two</option>   
     <option>Three</option>   
</select>
<script src=   
"https://code.jquery.com/jquery-3.3.1.min.js">   
</script>
<script>
$("option[value='Three']").remove()
</script>

I can not find a way to remove an option from a list if the option does not have a value.

I tried removing it with JQuery but it didn’t work well.

Thanks

5

Answers


  1. Chosen as BEST ANSWER

    This is my final code

    <select id="select1">   
         <option>One</option>   
         <option>Two</option>   
         <option>Three</option>   
    </select>
    <script src=   
    "https://code.jquery.com/jquery-3.3.1.min.js">   
    </script>
    <script>
    $("option:contains(Three)").remove()
    </script>

    It works and it is a efficient code


  2. You can use jQuery’s :contains()

    $("option:contains('Three')").remove()
    

    https://api.jquery.com/contains-selector/

    Login or Signup to reply.
  3. Add an id property to each option tag, then just select this id.
    if you need it to work dynamically you can construct some letters with an index number, eg. opt-1, opt-2 ....

    Login or Signup to reply.
  4. you can use loop on all #select1 option

    to be able to write an if condition to determine if option should be deleted or not

    $("#select1 option").each((index, option) => {
      if({your condition}) {
        $(option).remove();
      }
    });
    
    $("#select1 option").each((index, option) => {
      if($(option).text() === 'Three') {
        $(option).remove();
      }
    });
    <select id="select1">
      <option>One</option>
      <option>Two</option>
      <option>Three</option>
    </select>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js">
    </script>
    Login or Signup to reply.
  5. Select the option from select which needs to remove. Use jQuery remove() method to remove the option from the HTML document.

     $("option:contains('Three')").remove()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search