Show/hide elements based on a selected option with javascript

前端 未结 4 770
小鲜肉
小鲜肉 2020-12-19 23:38

I\'m currently working on a website (I\'m new to HTML, CSS, JavaScript and I haven\'t worked with JQuery) and I made a form in which users can select the type of candy they

4条回答
  •  情话喂你
    2020-12-20 00:21

    Please ignore some of the rude comments you received. Here's one way do accomplish what you're after

    // Function to add event listener to table
    var el = document.getElementById("selectC");
    el.addEventListener("change", function() {
      var elems = document.querySelectorAll('#noCandy1,#noCandy2,#noCandy3')
      for (var i = 0; i < elems.length; i++) {
        elems[i].style.display = 'none'
      }
      if (this.selectedIndex === 0) {
        document.querySelector('#noCandy1').style.display = 'block';
      } else if (this.selectedIndex === 1) {
        document.querySelector('#noCandy2').style.display = 'block';
      }else if (this.selectedIndex === 2) {
        document.querySelector('#noCandy3').style.display = 'block';
      }
    }, false);
    #noCandy1,#noCandy2,#noCandy3 {
      display:none;
    }

    The JavaScript above binds the change event handler to a function that first hides all your select elements containers. Note that using event handlers is preferred over writing inline JavaScript like you did in your example. Then, the code loops over your select elements containers and checks to see which one should be shown.

    For reference see:

    • https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
    • https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

提交回复
热议问题