I have multiple radio button sharing the same name. One of them has a hidden div next to It.
When the correct radio button is selected, I want to show/hide the div that is next it to it "if one is there"
Here is an example
Radio 1 Radio 2 Radio 3 Radio 4
Next to Radio 2 there is a hidden div. I want to show it when Radio 2 is selected. Then when Radio 4 is selected, I want to hide the Radio 2 div
Here is what I have done
$(function(){
function getGroupElement(value)
{
return '#group_' + value.replace(':', '_');
}
var previous;
$("input[type='radio']").click(function(e) {
// Store the current value on focus and on change
previous = $(this).val();
console.log('Current:' + previous);
}).change(function(e) {
var previousGroupId = getGroupElement(previous);
var newGroupName = $(this).data('show-group');
//Hide the previous Group
$(previousGroupId).hide();
if ( ! newGroupName){
return;
}
$(newGroupName).show();
});
});
My code above is not working because previous is set to the next selected item.
How can I hide/show the correct box?
If needed here is my HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<fieldset class="survey-control-fieldset">
<div class="survey-control-title">
Select a store
</div>
<div class="radio">
<label for="item_529"><input checked id="item_529" name=
"control_111" type="radio" value="112:529"> None</label>
</div>
<div class="radio">
<label for="item_530"><input id="item_530" name="control_111" type=
"radio" value="112:530"> Don't Know/No Answer</label>
</div>
<div class="radio">
<label for="item_532"><input data-show-group="group_112_532" id=
"item_532" name="control_111" type="radio" value="112:532">
Other</label>
<div id="group_112_532" style="display: none;">
<div class="form-group">
<label for="control_113">Specify Other Store Name</label>
<input class="form-control" id="control_113" name=
"control_113" placeholder="" type="text" value="">
</div>
</div>
</div>
<div class="radio">
<label for="item_531"><input id="item_531" name="control_111" type=
"radio" value="112:531"> Refused</label>
</div>
</fieldset>
</body>
</html>
Hide all the DIVs that are next to radios, then show the one next to the selected radio.
$(":radio").next("div").hide();
$(this).next("div").show();
If you give each of the hidden div's the same class name, you can just hide them all before you show the new one:
$('.hidden-divs').not(newGroupName).hide();
$(newGroupName).show();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.