Reputation: 391
I have 1 requirement I'm trying to achieve.
1) hide/unhide selection tag based on which radio button is selected
CodePen: DEMO
The user should ONLY be able to 'check' the unchecked radio button. E.g. If radio button A is 'checked', radio button B can be checked but not button A. vice versa.
$('#award, #year').click(function(){
// $('input[type="radio"]').not(':checked').prop('checked', false);
$("input[type='radio']").each(function() {
if($(this).is(':checked')){
$(this).prop('checked', true);
$('#awardOptions').toggleClass('hide');
$('#yearOptions').toggleClass('hide');
}else{
$(this).prop('checked', false);
$('#awardOptions').toggleClass('hide');
$('#yearOptions').toggleClass('hide');
}
});
});
Upvotes: 0
Views: 61
Reputation: 42384
The problem is that your if
condition is being met, then your else
condition is also being met. Considering you're toggling the visibility of the targets in both conditions, you're actually successfully showing the right element, then immediately hiding it again.
To resolve your problem, all you actually have to do is remove your else
statement entirely. This can be seen here.
Also, you don't actually need to set the checked
prop
to true
with $(this).prop('checked', true)
, as it is already true (as the logic enters the if($(this).is(':checked'))
conditional).
The above causes an issue where clicking on the selected input still has the toggle.
This can be resolved by simply changing the logic to isolate the two behaviours entirely, then enforcing the visibility of the desired element, and invisibility of the other:
// Toggle award/year slider
$('#award').click(function(){
$('#awardOptions').show();
$('#yearOptions').hide();
});
$('#year').click(function(){
$('#awardOptions').hide();
$('#yearOptions').show();
});
This works because it functions regardless of the current state; the hiding and showing is explicit rather than based on a toggle.
The existing CodePen has been modified to include this, which again can be found here.
Hope this helps! :)
Upvotes: 1
Reputation: 644
I found solution for you:
$('#award, #year').click(function(){
if($("input[type='radio']").is(':checked')){
$(this).prop('checked', true);
$('#awardOptions').addClass('hide');
$('#yearOptions').addClass('hide');
console.log("Add Class");
}else{
$(this).prop('checked', false);
$('#awardOptions').removeClass('hide');
$('#yearOptions').removeClass('hide');
console.log("Remove Class");
}
});
You should remove each() function, because it calls twice.
Upvotes: 0