[英]How to hide and show item if checkbox is checked
我試圖隱藏並根據是否選中復選框顯示區域。 我嘗試過一些選項,但是這個區域一直都是可見的,或者它一直都是隱藏的。
JavaScript:
$(document).ready(function () {
var mgift = $('#chkbxMGift input[type=checkbox]');
MshowHide();
mgift.change(function () {
MshowHide();
});
});
function MshowHide() {
var mgift = $('#chkbxMGift input[type=checkbox]');
var shcompany = $('#shcompany');
if (mgift.checked) {
shcompany.show();
} else {
shcompany.hide();
}
}
HTML:
<li>
<div class="info">
<asp:CheckBox ID="chkbxMGift" runat="server" Text="A matching gift will be made" ClientIDMode="Static"/>
</div>
</li>
<li id="shcompany">
<div class="info">
<label for="txtCompanyName">Company Name</label>
<asp:TextBox runat="server" ID="txtCompanyName" CssClass="narrow" />
</div>
<div class="info">
<label for="txtCompanyPhone">Company Phone Number</label>
<asp:TextBox runat="server" ID="txtCompanyPhone" CssClass="narrow" />
</div>
</li>
我怎樣才能正常工作?
試試這個代碼
$(document).ready(function () {
$('#chkbxMGift').click(function () {
var $this = $(this);
if ($this.is(':checked')) {
$('#shcompany').hide();
} else {
$('#shcompany').show();
}
});
});
希望它能解決你的問題
你的選擇器錯了。
var mgift = $('#chkbxMGift input[type=checkbox]');
這意味着您從父級#chkbxMGift
選擇子節點input
。
我相信這是你需要的選擇器:
var mgift = $('input#chkbxMGift[type=checkbox]');
以下是對您的代碼的一些改進:
$(document).ready(function () {
var mgift = $('input#chkbxMGift[type=checkbox]');
var shcompany = $('#shcompany');
// check for default status (when checked, show the shcompany)
if (mgift.attr('checked') !== undefined){
shcompany.show();
} else {
shcompany.hide();
}
// then simply toggle the shcompany on every change
mgift.change(function(){
shcompany.toggle();
});
});
jQuery的切換非常有用,並且在1.0版本中添加,因此您應該能夠使用它。
這是jsFiddle中的概念證明,只有最低限度:
這是從這個答案中偷來的:
$('.wpbook_hidden').css({
'display': 'none'
});
alert($(':checkbox:checked').attr('id'))
$(':checkbox').change(function() {
var option = 'wpbook_option_' + $(this).attr('id');
if ($('.' + option).css('display') == 'none') {
$('.' + option).fadeIn();
}
else {
$('.' + option).fadeOut();
}
});
在你問問之前先搜索類似的問題。 如果這可以解決您的問題,請給原作者一個信用
您是否嘗試過直接更改CSS? 如
document.getElementById("shcompany").style.display="none";
要么
document.getElementById("shcompany").style.visibility="hidden";
(或“可見”)
為什么在簡單的CSS屬性更改時可以使用JQuery?
只需更改div的類或修改它的樣式:
如果您希望它占用空間,即使隱藏時使用visibility:hidden
(分別是visibility:visible
)
如果你想隱藏時不要占用空間使用css display:none
(分別display:block
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.