我有几个单选按钮,其中一个是“其他”按钮。按钮。如果用户点击其他'我想显示一个文本框,询问更多信息。这是我的HTML和JS:
<div class="radio">
<label><input type="radio" name="optradio">Friend</label>
</div>
<div class="radio">
<label><input type="radio" name="optradio"> Worked together </label>
</div>
<div class="radio">
<label><input type="radio" name="optradio"> Studied together</label>
</div>
<div class="radio">
<label><input type="radio" name="other-radio" id="connection-invite-other-radio"> Other </label>
</div>
<div class="form-group" id="connection-invite-other">
<input type="text" class="form-control" >
</div>
JS:
$(document).ready(function(){
if($('#connection-invite-other-radio').is(':checked')) {
$('#connection-invite-other').show();
console.log("hi");
}
else {
$('#connection-invite-other').hide();
}
});
但这并不起作用。如果我做错了,请帮助我理解。谢谢!
答案 0 :(得分:2)
radio
需要具有相同的name
,在您的情况下optradio
。change
元素上使用radio
事件侦听器。
$(document).ready(function() {
$('input[type=radio]').change(function() {
if ($('#connection-invite-other-radio').is(':checked')) {
$('#connection-invite-other').show();
} else {
$('#connection-invite-other').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio">
<label>
<input type="radio" name="optradio">Friend</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optradio">Worked together</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optradio">Studied together</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optradio" id="connection-invite-other-radio">Other</label>
</div>
<div class="form-group" id="connection-invite-other">
<input type="text" class="form-control">
</div>
答案 1 :(得分:0)
您需要调用change
单选按钮事件来显示隐藏div。
$(document).ready(function(){
$('#connection-invite-other-radio').change(function(){
if($(this).is(':checked')) {
$('#connection-invite-other').show();
console.log("hi");
}
else {
$('#connection-invite-other').hide();
}
});
});