SHC MostWanted
SHC MostWanted

Reputation: 111

Using value from select element in switch loop (javascript)

I am trying to use values of options of dropdown menu in my loop, but i get uncaught error, all is undefined in filter1.

function filter1() {
    var x = document.getElementById("filter1").value;
    switch(x) {
        case all: 
        getElementsByClassName("1").style.display="none";
        break;
    } 
    console.log(x);
}

HTML:

 <select id="filter1" name="country" onchange="filter1()">
          <option value="all">All countries</option>
 </select>

Upvotes: 0

Views: 283

Answers (4)

eva.eis
eva.eis

Reputation: 36

may be you should use the next construction: function filter1(){ return document.getElementById("filter1").getAttributes("value").then(function(){ }) }

Upvotes: 0

marwils
marwils

Reputation: 473

Short answer: you forgot the quotes surrounding 'all'.

This should work:

function filter1(value) {
    switch(value) {
        case 'all': 
        //getElementsByClassName("1").style.display="none";
        console.log('all selected');
        break;
    } 
    console.log(value);
}
<select id="filter1" name="country" onchange="filter1(this.value)">
    <option value="all">All countries</option>
    <option value="us">US</option>
</select>

Upvotes: 0

prasanth
prasanth

Reputation: 22510

You are missing the quotes to assign string in case 'all'.And add one option greater then only perform the change function

Change document.getElementsByClassName("1")[0] instead of getElementsByClassName("1") .Because the classname is the multiple selector

function filter1() {
  var x = document.getElementById("filter1").value;
  switch (x) {
    case 'all':
     console.log('work')
      //document.getElementsByClassName("1")[0].style.display = "none";
      break;
  }
  console.log(x);
}
<select id="filter1" name="country" onchange="filter1()">
          <option value="all">All countries</option>
          <option value="one">All one</option>
 </select>

Upvotes: 1

Puneet
Puneet

Reputation: 325

Use This instead

function filter1() {
    var x = document.getElementById("filter1").value;
    switch(x) {
        case "all": 
        getElementsByClassName("1").style.display="none";
        break;
    } 
    console.log(x);
}

Upvotes: 0

Related Questions