Home > front end >  Remove option with certain text from dropdown menu
Remove option with certain text from dropdown menu

Time:03-24

In my Django app (using {% load crispy_forms_tags %}) I have a following dropdown menu:

<div id="div_id_report_division" >
<label for="id_report_division" >Test<span ></span</label>
<div >
<select name="report_division"  required="" id="id_report_division">
  <option value="" selected="">---------</option>
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
  <option value="4">D</option>
  <option value="5">E</option>
</select> </div> </div>

I wish to remove option number 5 on page load. My Javascript on post.html with everything is:

     <script type="text/javascript">
         function on_load(){
            /*
            option 1.:
            document.querySelector('id_report_division option[value=5]').remove();
            option 2.:
            var x = document.getElementById('id_report_division');
            x.remove(5);
            option 3.:
            document.querySelector('#id_report_division option[value=5]').remove();
            const first = document.querySelector("[id='id_report_division']");
            */

            document.querySelector("[id='id_report_division' option[value=5]]").remove();

            }
         on_load();
    </script>

How can I easly remove this option? It would be better if I could remove option where text is E, in case that value changes. But there will always be only one text 'E', no need to itterate.

CodePudding user response:

You can iterate the select options list, check the inner text and remove like so:

var selectobject = document.getElementById("id_report_division");
for (var i=0; i<selectobject.length; i  ) {
    if (selectobject.options[i].text == 'E')
        selectobject.remove(i);
}
  • Related