Переключение между вкладками с помощью флажков - PullRequest
0 голосов
/ 31 декабря 2018

У меня есть раздел вкладок с 3 разделами, каждая вкладка имеет свой собственный заголовок и содержание.

Но я не хочу показывать все 3 вкладки, только то, что пользователь выбирает, установив соответствующий флажок,Есть 3 связанных флажка, по одному для каждой вкладки.

Вот код:

//Function to hide all siblings but leave the clicked one
function hideAllChildrenButOne(parentId, toRevealId) {
	$('#' + parentId).children().css('display', 'none');
	$('#' + toRevealId).css('display', 'block');
}

//Function to show the tab header and content when a checkbox is checked
function showSection(parentId, toRevealId) {
	var relatedSection = $('#' + toRevealId).attr('data-section');
	$('#' + toRevealId).toggleClass('inline-block');
	$('#' + toRevealId).siblings().removeClass('tab_active');
	$('#' + toRevealId).toggleClass('tab_active');
	$('#' + relatedSection).toggleClass('active');
	$('#' + relatedSection).siblings().removeClass('active');
	$('#' + relatedSection).toggleClass('block');
	
	if ($('input[data-header=' + toRevealId + ']').is(':checked')) {
	}else{
	}
}

$(document).ready(function() {

	//On clicking a tab header('Father', 'Mother', 'Brother')
	$('.tab-header').click(function(event) {
		$(this).addClass('tab_active').siblings().removeClass('tab_active');
	    var related_section = $(this).attr('data-section');
	    hideAllChildrenButOne('relative_content', related_section);
	});

	//On changing any checkbox with name=relative[]
	$("input[name='relative[]']").change(function() {
	    var self = $(this);
	    console.log(self.value);
	    showSection('relative_tabs', self.attr('data-header'));
	});

});
.relative_container{
    position: relative;
    padding: 45px 15px 15px;
    margin: 0 -15px 15px;
    border-color: #e5e5e5 #eee #eee;
    border-style: solid;
    border-width: 1px 0;
    -webkit-box-shadow: inset 0 3px 6px rgba(0,0,0,.05);
    box-shadow: inset 0 3px 6px rgba(0,0,0,.05);
}
@media (min-width: 768px){
	.relative_container {
	    margin-right: 0;
	    margin-left: 0;
	    background-color: #fff;
	    border-color: #ddd;
	    border-width: 1px;
	    border-radius: 4px 4px 0 0;
	    -webkit-box-shadow: none;
	    box-shadow: none;
	}
}
.relative_tabs{
	margin-bottom: 15px;
	border-bottom: 1px solid #ddd;
	list-style: none;
	padding: 7px 0;
}
.relative_tabs:before{
	display: table;
	content: " ";
}	
.tab-header{
	display: none;
	margin-bottom: -1px;
}
.tab-header>a{
	margin-right: 2px;
    line-height: 1.42857143;
    border: 1px solid transparent;
    border-radius: 4px 4px 0 0;
    padding: 9px 15px;
    text-decoration: none;
    cursor: pointer;
}
.tab-header.tab_active>a{
	color: #555;
    cursor: default;
    background-color: #fff;
    border: 1px solid #ddd;
    border-bottom-color: transparent;
}
.relative_content div{
	display: none;
}
.relative_content>div.active{
	display: block;
}
.tab-content{
	display: none;
}
.hidden{
	display: none;
}
.inline-block{
	display: inline-block;
}
.block{
	display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
	<label>Father<input type="checkbox" name="relative[]" value="Father" data-header="father-tab"></label>
	<label>Mother<input type="checkbox" name="relative[]" value="Mother" data-header="mother-tab"></label>
	<label>Guardian<input type="checkbox" name="relative[]" value="Guardian"></label>
	<label>Other<input type="checkbox" name="relative[]" value="Other"></label>
	<div class="relative_container">
		<div class="relative_header">
			<ul class="relative_tabs" id="relative_tabs">
				<li id="father-tab" data-section="Father_info" class="tab-header">
					<a>Father</a>
				</li> 
				<li data-section="Mother_info" class="tab-header" id="mother-tab">
					<a>Mother</a>
				</li>
			</ul>
		</div>
		<div class="relative_content" id="relative_content">
			<div class="tab-content" id="Father_info">Father Info</div>
			<div class="tab-content" id="Mother_info">Mother Info</div>
		</div>
	</div>
</form>

Возникла проблема:

При установке более 1 флажка отображаются связанные вкладки, но только последняя отмеченнаяактивен, но когда я снимаю галочку со всех из них, кроме одного, отмеченный не активен.

Поэтому, если пользователь установил несколько флажков и установил все, кроме одного, этот должен стать активным.

Ответы [ 2 ]

0 голосов
/ 02 января 2019

Думаю, пара изменений в html и javascript поможет вам достичь желаемого результата.В html я использую почти одинаковые идентификаторы для вкладок и содержимого (просто diff - это содержимое с суффиксом _info).

См. Фрагмент ниже:

$(document).ready(function() {
	//On clicking a tab header('Father', 'Mother', 'Brother')
    $('.tab-header').click(function(event) {
      $(this).addClass('tab_active').siblings().removeClass('tab_active');
	    $('#relative_content').children().css('display', 'none');
      $('#' + $(this).attr('id')+'_info').css('display', 'block');
    });

    //On changing any checkbox with name=relative[]
    $("input[name='relative[]']").change(function() {
      $('#' + $(this).data('header')).toggleClass('inline-block');
      
      if($(this)[0].checked){
         $('#' + $(this).data('header')).click();
      }else{
	      $('#relative_content').children().css('display', 'none');
        if($('.inline-block.tab_active').length == 0 && $('.tab-header.inline-block').length>0){
          $($('.tab-header.inline-block')[0]).click();
        }else{
          $($('.inline-block.tab_active')[0]).click();
        }
      }
	  });
});
.relative_container{
    position: relative;
    padding: 45px 15px 15px;
    margin: 0 -15px 15px;
    border-color: #e5e5e5 #eee #eee;
    border-style: solid;
    border-width: 1px 0;
    -webkit-box-shadow: inset 0 3px 6px rgba(0,0,0,.05);
    box-shadow: inset 0 3px 6px rgba(0,0,0,.05);
}
@media (min-width: 768px){
	.relative_container {
	    margin-right: 0;
	    margin-left: 0;
	    background-color: #fff;
	    border-color: #ddd;
	    border-width: 1px;
	    border-radius: 4px 4px 0 0;
	    -webkit-box-shadow: none;
	    box-shadow: none;
	}
}
.relative_tabs{
	margin-bottom: 15px;
	border-bottom: 1px solid #ddd;
	list-style: none;
	padding: 7px 0;
}
.relative_tabs:before{
	display: table;
	content: " ";
}	
.tab-header{
	display: none;
	margin-bottom: -1px;
}
.tab-header>a{
	margin-right: 2px;
    line-height: 1.42857143;
    border: 1px solid transparent;
    border-radius: 4px 4px 0 0;
    padding: 9px 15px;
    text-decoration: none;
    cursor: pointer;
}
.tab-header.tab_active>a{
	color: #555;
    cursor: default;
    background-color: #fff;
    border: 1px solid #ddd;
    border-bottom-color: transparent;
}
.relative_content div{
	display: none;
}
.relative_content>div.active{
	display: block;
}
.tab-content{
	display: none;
}
.hidden{
	display: none;
}
.inline-block{
	display: inline-block;
}
.block{
	display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
	<label>Father<input type="checkbox" name="relative[]" value="Father" data-header="father-tab"></label>
	<label>Mother<input type="checkbox" name="relative[]" value="Mother" data-header="mother-tab"></label>
	<label>Guardian<input type="checkbox" name="relative[]" value="Guardian" data-header="guardian-tab"></label>
	<label>Other<input type="checkbox" name="relative[]" value="Other" data-header="other-tab"></label>
	<div class="relative_container">
		<div class="relative_header">
			<ul class="relative_tabs" id="relative_tabs">
				<li id="father-tab" data-section="Father_info" class="tab-header">
					<a>Father</a>
				</li> 
				<li data-section="Mother_info" class="tab-header" id="mother-tab">
					<a>Mother</a>
				</li>
				<li data-section="Guardian_info" class="tab-header" id="guardian-tab">
					<a>Guardian</a>
				</li>
				<li data-section="Other_info" class="tab-header" id="other-tab">
					<a>Other</a>
				</li>
			</ul>
		</div>
		<div class="relative_content" id="relative_content">
			<div class="tab-content" id="father-tab_info">Father Info</div>
			<div class="tab-content" id="mother-tab_info">Mother Info</div>
			<div class="tab-content" id="guardian-tab_info">Guardian Info</div>
			<div class="tab-content" id="other-tab_info">Other Info</div>
		</div>
	</div>
</form>

Вы можете проверить это здесь также.

0 голосов
/ 01 января 2019

Вот очень упрощенный пример, который может помочь. По какой-то причине StackSnippet не работает, поэтому я также сделал jsFiddle того же самого для демонстрации.

Обратите внимание, что я использовал класс "активный" как маркер (так ли этовкл / выкл?) и добавить css. Вы можете использовать другое имя, если вы уже используете «active» для чего-то другого.

jsFiddle Demo

$('[id^=cb]').click(function(){
  var cb = this.id.split('_')[1];
  if ( $('div#d_'+cb).hasClass('active') ){
    $('div#d_'+cb).hide().removeClass('active');
  }else{
    $('div#d_'+cb).show().addClass('active');
  }
});
div{display:inline-block;height:50px;width:50px;margin-right:10px;display:none;}
#d_1{background:yellow;}
#d_2{background:pink;}
#d_3{background:green;}
#d_4{background:orange;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="cb_1" type="checkbox" />
<input id="cb_2" type="checkbox" />
<input id="cb_3" type="checkbox" />
<input id="cb_4" type="checkbox" />
<section id="wrapper">
  <div id="d_1"></div>
  <div id="d_2"></div>
  <div id="d_3"></div>
  <div id="d_4"></div>
</section>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...