Show/hide elements based on a selected option with javascript

前端 未结 4 761
小鲜肉
小鲜肉 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:18

    The best way to approach this scenario would be to use a function. This will not only save you from a lot of unnecessary code, but also make your website more readable and maintainable.

    For each option, instead of using

    onclick="document.getElementById('noCandy1').style.display='block';,

    Use

    onclick = "show_form('noCandy1')", where noCandy1 is your desired form part.

    Then you would declare show_form() in the javascript like such:

    function show_form(candy){
        document.getElementsByClassName('candy_form').style.display = 'none'; //Hide forms
        document.getElementById(candy).style.display='block'; //Show desired form
        return true;
    }
    

    Here is how the HTML should be structured for this to work:

    
        
    Form for Lollipops
    Form for Haribo Gummies
    Form for Gum.

提交回复
热议问题