Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make specific options to appear in select menu?

I have two select fields in a program. Both select fields contain options with values 1 to 10. the code is as below:

<select id="noc">
       <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><br/>

<!--Some text---->

<select id="po">
       <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>

I want to achieve the following effect using JavaScript :

(Only for example) If the user has selected the option 8 in the first select field (id="noc"), the options below 8 (i.e. 9 and 10) should not be visible in the second select field (id="po").

like image 538
Praneet Dixit Avatar asked May 31 '20 13:05

Praneet Dixit


1 Answers

You can do it with using onChange method and with querySelectorAll.

display or visibility attributes doesn't work for cross browsers. So you should recreate options.

var noc=document.getElementById("noc");
var po=document.getElementById("po");
var options=po.querySelectorAll("option");
function nochange(){
  po.innerHTML="";
  [...options].filter(x=>parseInt(x.value)<=parseInt(noc.value)).forEach(x=>{po.append(x)})
  po.value=noc.value;
  
}
<select id="noc"onChange="nochange()">
       <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><br/>

<!--Some text---->

<select id="po">
       <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>
like image 80
mr. pc_coder Avatar answered Sep 28 '22 22:09

mr. pc_coder