I have a form with a number of questions on it, some are a yes/no. If yes is selected, it will display a text box asking for more info. I've got the show/hide part to work but once I click a button elsewhere on the page it then hides the textarea and i lose the info.
Currently I'm using this: JQuery
$(document).ready(function () {
$(".text").hide();
$("#r1").click(function () {
$(".text").show();
});
$("#r2").click(function () {
$(".text").hide();
});
});
HTML
<input type="radio" name="radio1" id="r1" value="Yes">
<input type="radio" name="radio1" id="r2" value="No">
<div class="text">
<textarea class="form-control" rows="3" id="comment"></textarea>
</div>
You need to target the textarea relative to the checkboxes being checked.
change
event, rather than click
(there are other ways of changing a radio button other than clicking it) .nextAll()
and .first()
to get the relevant textarea toggle()
with this.value == 'Yes'
which will be expressed as a true or false value and therefore show or hide the element respectively. $('.text').hide();
$('input[type=radio]').on('change', function(){
$(this).nextAll('.text').first().toggle( this.value == 'Yes' );
});
OP here, if anyone is looking for the answer using buttons instead I resolved the issue with advice from Norlihazmey Ghazali who mentioned to target the specific id. For example:
<div class="btn-group btn-toggle">
<input type="button" class="btn btn-default" id="taxliabl1" value="Yes"></input>
<input type="button" class="btn btn-default" id="taxliabl2" value="No"></input>
<br>
<div class="taxliabltext">
<br>
<textarea class="form-control" rows="3" id="comment"></textarea>
<br>
Jquery:
$(document).ready(function () {
$(".taxliabltext").hide();
$("#taxliabl1").click(function () {
$(".taxliabltext").show();
});
$("#taxliabl2").click(function () {
$(".taxliabltext").hide();
});
});
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.