Information



Tags



Share

How to combine two select form elements in JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement



Definition

While creating a user-friendly form to collect information in order to save it to the database, as a possible concomitant, you might need to implement sub-categories by using select form elements. And therefore, you have to combine two or more select form elements. I will show you how to do that in JavaScript in this tutorial.

Code

First of all, get elements of the category and the sub-category.

Create an object containing car types depending on the selected year.

In the printOptions function, remove all former option elements by using the query selector and add new option elements on the sub-category relative to the selected year.

When the category value is changed, according to the value, print car types in the associated array as new option elements.

Also, by clicking the sub-category, you can display the selected car type.


var category = document.getElementById("category");
var subcategory = document.getElementById("sub-category");

var cars = {
1997: ["Audi", "BMW", "Toyota", "Showroom", "Cadillac"],
1998: ["Jeep", "General Motors", "Ford"],
1999: ["Honda", "Volkswagen", "Nissan", "Opal"]
};

function printOptions(cars){
var removeOptions = subcategory.querySelectorAll("option");

for(var i=0;i<removeOptions.length;i++){
subcategory.removeChild(removeOptions[i]);
}

for(i=0;i<cars.length;i++){
options = document.createElement("OPTION");
options.value = cars[i];
options.innerHTML = cars[i];
subcategory.add(options);
}
}

category.addEventListener("change", function(){
var data = category.value;
var options;
if(data == 1997){
printOptions(cars["1997"]);
}else if(data == 1998){
printOptions(cars["1998"]);
}else if(data == 1999){
printOptions(cars["1999"]);
}
});

subcategory.addEventListener("change", function(){
document.getElementById("test").innerHTML = subcategory.value;
});

Result:

Please click to view...