1

I'm a beginner and I'm try to set up a form. I have written the html/css code. What I wanted to do is to click on a level of study such as Bachelors, I want all the courses under bachelors to display in the second box (choose course) while hiding the rest of the courses in the box.

label {
  font-family: sans-serif;
  font-size: 1rem;
  padding-right: 10px;
}

select {
  font-size: .9rem;
  padding: 2px 5px;
}
<h2>This is a form</h2>

            <p>Online Application:</p>

                <form id="form1" action="#">
                    <label for="school-select">Choose levels of study:</label>

                    <select id="level-select">
                        <option value="">--Please choose an option--</option>
                        <option value="bachelor">Bachelors</option>
                        <option value="postgraduates">Postgraduates</option>
                        <option value="phd">PhD</option>
                        
                    </select>
                    
                </form>
                <br>

                <form id="form2" action="#">
                    <label for="course-select">Choose course:</label>

                    <select id="cour">
                        <optgroup label="Bachelors">
                            <option>Microbiology</option>
                            <option>chemistry</option>
                            <option>physics</option>
                        </optgroup>
                        <optgroup label="Postgraduates">
                            <option>computer</option>
                            <option>biology</option>
                            <option>accounting</option>
                        </optgroup>

                        <optgroup label="PhD">
                            <option>business</option>
                            <option>fisheries</option>
                            <option>agric</option>
                        </optgroup>
                    </select>
                    
                </form>

6 Answers 6

1

Here, I've come up with a simple solution to this. I've changed your html a little bit. I've set the same values as their optgroup's label so that we can choose the specific optgroup for being shown. So the solution is simple:

  1. Hide all the options of the second box.
  2. Show the one by courses.querySelector('[label="' + value + '"]'); this, where value is your first box's selected value.

Have a look at the code snippet below:

function getLevels() {
    var value = document.getElementById("level-select").value;

    if (value) {
        var courses = document.querySelector("#cour");
        var all_options = courses.querySelectorAll('optgroup');
        var show_courses = courses.querySelector('[label="' + value + '"]');

        all_options.forEach(function (element) {
            element.style.display = "none";
        });

        show_courses.style.display = "block";
    }

}
<h2>This is a form</h2>

<p>Online Application:</p>

<form id="form1" action="#">
    <label for="school-select">Choose levels of study:</label>

    <select id="level-select" onchange="getLevels()">
        <option value="">--Please choose an option--</option>
        <option value="Bachelors">Bachelors</option>
        <option value="Postgraduates">Postgraduates</option>
        <option value="PhD">PhD</option>
    </select>

</form>
<br>

<form id="form2" action="#">
    <label for="course-select">Choose course:</label>

    <select id="cour">
        <option selected>--Choose Course--</option>
        <optgroup label="Bachelors">
            <option>Microbiology</option>
            <option>chemistry</option>
            <option>physics</option>
        </optgroup>
        <optgroup label="Postgraduates">
            <option>computer</option>
            <option>biology</option>
            <option>accounting</option>
        </optgroup>

        <optgroup label="PhD">
            <option>business</option>
            <option>fisheries</option>
            <option>agric</option>
        </optgroup>
    </select>

</form>

Sign up to request clarification or add additional context in comments.

2 Comments

Thumb Up...exactly what I needed
@Ayplux, My pleasure :)
1

Just add onClick event in <option> tag?

<option onClick="myFunction()">Microbiology</option>

<script>
function myFunction() {
  //do what you want..
}
</script>```

Comments

1

Add a onchange event to the select field, and push the value to a function like;

<select id="level-select" onchange="setLevel(this.value)">

Hide all option groups in css;

#cour optgroup {
    display:none;
}

Give all option groups a unique ID containing the value of the first select, like;

<optgroup label="Bachelors" id="course_bachelor">

And now the function for the onchange event could be something like this;

    function setLevel (val) {
        var elements = document.getElementsByTagName('optgroup');

        // Loop through all elements and check if they are hidden or shown
        for(var i=0; i < elements.length; i++) {
            if (elements[i].id === 'course_' + val) {
                elements[i].style.display = 'block';
            } else {
                elements[i].style.display = 'none';
            }
        }
    }

Comments

1

label {
  font-family: sans-serif;
  font-size: 1rem;
  padding-right: 10px;
}

select {
  font-size: .9rem;
  padding: 2px 5px;
}
<h2>This is a form</h2>

            <p>Online Application:</p>

                <form id="form1" action="#">
                    <label for="school-select">Choose levels of study:</label>

                    <select id="level-select">
                        <option value="">--Please choose an option--</option>
                        <option value="bachelor">Bachelors</option>
                        <option value="postgraduates">Postgraduates</option>
                        <option value="phd">PhD</option>
                        
                    </select>
                    
               
                <br>

                    <label for="course-select">Choose course:</label>

                    <select id="cour">
                       
                    </select>
                    
                </form>

var select = document.getElementById("level-select");
select.onchange(() => {
if(select.value == 'bachelor') {
document.getElementById("cour").value == "<optgroup label="Bachelors">
                        <option>Microbiology</option>
                        <option>chemistry</option>
                        <option>physics</option>
                    </optgroup>"
}

})

Do this for all the conditions.

3 Comments

I think it's bad practice to inject html with javascript, because it makes the code unreadable most of the time. Also you can introduce xss vulnerabilities.
Then you should use some simple styling like collapse in bootstrap. That will also help.
Indeed! I think it's better to use a framework than vanilla stuff anyways, because the code is more structured that way and most of the boring code is already done. ;)
1

You'll need to use some Javascript to do this. Here's one solution that could work for you.

I've updated some of your html names (first dropdown values to exactly match the 'optgroup' labels in your second dropdown). Also added some CSS to have the options for the courses dropdown to not show until you've selected a valid option, which prevents the user from, say, going back to change the first dropdown value while the second dropdown value stays the same. Always 'idiot-proof' your UI:

//grab both dropdowns and store in variable
var levelSelectDropdown = document.querySelector('#level-select');
var coursesDropdown = document.querySelector('#cour');

//create an on 'change' event for first dropdown 
levelSelectDropdown.addEventListener('change', levelDropdownChange);

function levelDropdownChange(e){
  var selectedLevelOfStudy = e.target.value;
  var coursesGroups = coursesDropdown.querySelectorAll('optgroup');
  
  //this basically hides the 'default' empty option that's auto-selected
  //by default
  coursesDropdown.querySelector('option[value="default"]').style.display = 'none';
  
  //loop through all 'optgroup' items in second dropdown (coursesGroups)
  coursesGroups.forEach(function(element){
    //default course dropdown to first element (this essentially resets
    //the course dropdown each time level of study dropdown is changed
    coursesDropdown.selectedIndex = 0;
    //make sure all optgroups are hidden
    element.style.display = 'none';
    //only display optgroup whose label matches the value selected
    //from first dropdown
    if(element.getAttribute('label') == selectedLevelOfStudy){
      element.style.display = 'block';
    }
  })
}
label {
  font-family: sans-serif;
  font-size: 1rem;
  padding-right: 10px;
}

select {
  font-size: .9rem;
  padding: 2px 5px;
}

#cour optgroup {
  display:none;
}
<h2>This is a form</h2>
  <p>Online Application:</p>
  <form id="form1" action="#">
    <label for="school-select">Choose levels of study:</label>
    <select id="level-select">
      <option value="">--Please choose an option--</option>
      <option value="bachelors">Bachelors</option>
      <option value="postgraduates">Postgraduates</option>
      <option value="phd">PhD</option>
    </select>
  </form>
  <br>
  <form id="form2" action="#">
    <label for="course-select">Choose course:</label>
    <select id="cour">
      <option value="default"></option>
      <optgroup label="bachelors">
        <option>Microbiology</option>
        <option>chemistry</option>
        <option>physics</option>
      </optgroup>
      <optgroup label="postgraduates">
        <option>computer</option>
        <option>biology</option>
        <option>accounting</option>
      </optgroup>
      <optgroup label="phd">
        <option>business</option>
        <option>fisheries</option>
        <option>agric</option>
      </optgroup>
    </select>
  </form>

Comments

0

label {
  font-family: sans-serif;
  font-size: 1rem;
  padding-right: 10px;
}

select {
  font-size: .9rem;
  padding: 2px 5px;
}

 
<h2>This is a form</h2>

            <p>Online Application:</p>

                <form id="form1" action="#">

   <script lang="javascript">
function onLevelofStudyChange()
{
  var selectedLevel=document.getElementById("level-select").value;
  var course = document.querySelector("#cour");
  var alloption = course.querySelectorAll('optgroup')
  var getByLabel = course.querySelector('[label="'+selectedLevel+'"]');

   
//Hide all Optgroups
alloption.forEach(function(element){
 element.style.display = "none";
});


if(getByLabel!=null)
   getByLabel.style.display = "block";

}
</script>
                    <label for="school-select">Choose levels of study:</label>

                    <select id="level-select" onchange="onLevelofStudyChange()">
                        <option value="">--Please choose an option--</option>
                        <option value="bachelor">Bachelors</option>
                        <option value="postgraduates">Postgraduates</option>
                        <option value="phd">PhD</option>
                        
                    </select>
                    
                </form>
                <br>

                <form id="form2" action="#">
                    <label for="course-select">Choose course:</label>

                    <select id="cour">
                        <option>--Please Choose course--</option>
                        <optgroup label="bachelor" style="display:none">
                            <option>Microbiology</option>
                            <option>chemistry</option>
                            <option>physics</option>
                        </optgroup>
                        <optgroup label="postgraduates" style="display:none">
                            <option>computer</option>
                            <option>biology</option>
                            <option>accounting</option>
                        </optgroup>

                        <optgroup label="phd" style="display:none">
                            <option>business</option>
                            <option>fisheries</option>
                            <option>agric</option>
                        </optgroup>
                    </select>
                    
                </form>

Try this, it should work also note I have changed Optgroup label inorder to match the value of first dropdown

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.