Search code examples
javascriptjqueryhideshow

Hide certain inputs and show others using a switch button in jQuery


Hello Stackoverflow community, hope that you're doing well, what I'm trying to do is when I click the switch button I want it to hide certain inputs and show others, my code is a form to add students and teachers, since there are cummon inputs I tought about hide the uncummon one when I press the switch button and when I click it again do the opposite but all of that seem to be failed, I can only hide some and when I click it again it won't work, here what I did:

The Jquery code:

$(document).ready(function(){
    $('.teacher').hide();
    $('.switch').click(function(){
        $('.student').hide();
        $('.teacher').show();
    });
});

The HTML code:

 <label>Student&nbsp;</label>
                                    <label class="switch">
                                      <input type="checkbox" id="switchVal" value="0">
                                      <span class="slider"></span>
                                    </label> 
                                    <label>&nbsp;Teacher</label>

Solution

  • $('.teacher').hide();
      $('.switch').click(function() {
        $('.student').toggle();
        $('.teacher').toggle();
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='student'>Student</div>
    <div class="switch">
      <input type="checkbox" id="switchVal" value="0">
      <span class="slider"></span>
    </div>
    <div class='teacher'>Teacher</div>