Javascript select tag

Javascript <select> 

Javascript <select> 

 

1.Get tag "select"

//1.
    var element = document.getElementById('selectName');

//2. 
    var tagName = document.getElementsByTagName("select");

//3.
   var byClass = document.getElementsByClassName("class");

2.Get option

//1.
  var option = document.getElementById("select").options[index];

//2.
  var select = document.getElementById("select").options;
  //object
  var option = select[index];

  //get value, text, index
  var x = option.value;
  var y = option.text;
  var z = option.index;

//3. 
  var select = document.getElementById("select");
  var optionIndex = select.selectedIndex; 
  //The index starts at 0. If no option is selected, the value returned is -1


3.Add option

//1.
var select = document.getElementById("select");
var newoption = document.createElement("option");
newoption.text = "kiwi";
select.add(newoption,index);
//add a "kiwi" option at index position in select drop-down list


//2.
      var resultList = data.CategoryItemList; //List <string>
      for (var i = 0; i < resultList.length; i++) {
            var option = document.createElement("OPTION");  // Create a <option> element
            var t = document.createTextNode(resultList[i]); // Create a text node
            option.appendChild(t);                     // Append the text to <option>
            document.getElementById("CategoryFilter").appendChild(option);  // Append <option> to CategoryFilter
        }

4.Remove option

var select = document.getElementById("select");
select.remove(index); 

5.Change the options

<!DOCTYPE html>
<html>
<body>   

<select id="car" onchange="ChangeCarList()"> 
  <option value="">-- Car --</option> 
  <option value="VO">Volvo</option> 
  <option value="VW">Volkswagen</option> 
  <option value="BMW">BMW</option> 
</select> 

<select id="carmodel"></select> 

<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];

function ChangeCarList() {
    var carList = document.getElementById("car");
    var modelList = document.getElementById("carmodel");
    var selCar = carList.options[carList.selectedIndex].value;
    while (modelList.options.length) {
        modelList.remove(0);
    }
    var cars = carsAndModels[selCar];
    if (cars) {
        var i;
        for (i = 0; i < cars.length; i++) {
            var car = new Option(cars[i], i);
            modelList.options.add(car);
        }
    }
} 
</script>

</body>
</html>

 

參考網址 : W3