OLA
OLA

Reputation: 971

Need to select text of selected dropdown using JavaScript

I have a dropdown with values. I have an array array with a list of values that will match the drop down values. If the value of text option of the dropdown exists in the array, it shouldn't show in the dropdown as an option. I am stuck on the approach I should use. This is what I have so far.

HTML

Car Plates: 
<select title='car/id' id='car_x0020_Plate_x002f'>
  <option selected="selected" value="0">none</option>
  <option value="16">233-jj2</option>
  <option value="10">934-zxy</option>
  <option value="90">330-nbh</option>
  <option value="11">930-orj</option>
</select>

JavaScript

var hideOption = ['233-jj2', '330-nbh']

var e = document.querySelector([id^='car']);
var strUser = e.value;
                               
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;

for (var x=0; x<hideOption.length; x++){
  if (hideOption[x] === strUser){
    //remove from dropdown
  }
}

Upvotes: 1

Views: 220

Answers (4)

Taha Halabi
Taha Halabi

Reputation: 171

I made your idea in a very simple way, if you have any question please tell me

var hideOption = ['233-jj2', '330-nbh'],
    select = document.getElementById("select");

for (let i = 0; i < hideOption.length; i = i + 1) {
    for (let t = 1; t < select.options.length; t = t + 1) {
        if (hideOption[i] == select.options[t].textContent) {
            select.options[t].remove();
        }
    }
}
Car Plates: 
<select title='car/id' id='select'>
  <option selected="selected" value="0">none</option>
  <option value="16">233-jj2</option>
  <option value="10">934-zxy</option>
  <option value="90">330-nbh</option>
  <option value="11">930-orj</option>
</select>

Upvotes: 1

Bouh
Bouh

Reputation: 1392

var options = document.querySelector("[id^='car']").children;
var hideOption = ['233-jj2', '330-nbh']

for (var i = 0; i < options.length; i++){
    if(hideOption.indexOf(options[i].text) > -1){
        options[i].remove();
    }
}

Upvotes: 0

Taha Halabi
Taha Halabi

Reputation: 171

// remove from dropdown use this code to remove from dropdown e.removeChild(e.options[e.selectedIndex])

you can use this also e.selectedOptions[0].remove()

Upvotes: 1

symlink
symlink

Reputation: 12209

var hideOption = ['233-jj2', '330-nbh']

var e = document.querySelector("[id^='car']");
var selTextArr = Array.from(e.options).map(option => option.text)
                               
for (var x=0; x<selTextArr.length; x++){
  if (hideOption.includes(selTextArr[x])){
    e.remove(x)
  }
}
Car Plates: 
<select title='car/id' id='car_x0020_Plate_x002f'>
  <option selected="selected" value="0">none</option>
  <option value="16">233-jj2</option>
  <option value="10">934-zxy</option>
  <option value="90">330-nbh</option>
  <option value="11">930-orj</option>
</select>

Upvotes: 0

Related Questions