CodeAndCode
CodeAndCode

Reputation: 79

JQuery tabs using element ID

I have two buttons and two divs with paragraphs. I would like to create tabs but I don't know how to show div when I click button. The thing is that I can't add any new class or ID. I have to use available classes and IDs. I was looking for solution using button and div ID.

For example:

First button has ID "tab_button_one" and first div has ID input_one. Is there a way to create tab switch by using "_one" form ID?

<button id="tab_button_one" class="btn active-button">Button one</button>
<button id="tab_button_two" class="btn">Button two</button>

<div id="input_one" class="input active-input">
  <p>input one</p>
</div>

<div id="input_two" class="input">
  <p>input two</p>
</div>


<style>
.btn{
  background-color: transparent;
  border: 1px solid #000;
  padding: 10px;
  color: #000;
  cursor: pointer;
}

.btn.active-button{
  background-color: #0000b2;
  border-color: #0000b2;
  color: #fff;
}

.input{
  border: 1px solid #000;
  padding: 10px;
  margin: 10px 0;
  display: none;
}

.input.active-input{
  display: block;
}

</style>

<script>
  $('.btn').click(function(){
    if( $(this).hasClass('active-button') == false){
      var id = $(this).attr('id');
      $('.btn').removeClass('active-button');
      $(this).addClass('active-button');  
            $('.input').removeClass('active-input');
    }
  });
</script>

https://jsfiddle.net/7hotd8z2/2/

Upvotes: 1

Views: 158

Answers (1)

user10275798
user10275798

Reputation:

You could do something along these lines, assuming the ids always follow this structure:

 $('.btn').click(function(){
    if( $(this).hasClass('active-button') == false){
      var id = $(this).attr('id').split('_')[2];
      $('.btn').removeClass('active-button');
      $(this).addClass('active-button');  
      $('.input').removeClass('active-input');
      $('#input_'+id).addClass('active-input');
    }
  });

This seems to be in line with what you are doing with the tabs.

Upvotes: 1

Related Questions