复选框显示隐藏字段 - 不工作onload [英] Checkbox shows hidden field - not working onload
问题描述
如果选中复选框,我使用这个可能是丑陋的javascript来显示一个文本框(在li标记及其标签中)。
I am using this probably ugly javascript to show a text box (in a li tag plus its label) if a checkbox is checked.
$("#li-2-21").css("display","none");
$("#Languages-spoken-and-understood-8").click(function(){
if ($("#Languages-spoken-and-understood-8").is(":checked"))
{
$("#li-2-21").show("fast");
}
else
{
$("#li-2-21").hide("fast");
}
});
这很好,但如果加载网页并且复选框已经选中, #li-2-21会自动隐藏。
That works fine but it doesn't work if a page is loaded and the checkbox is already checked because the #li-2-21 gets automatically hidden.
我需要创建一个读取复选框状态的函数吗?或者有更简单的方法吗?
Do I need to create a function that reads the state of the checkbox? Or is there a simpler way?
哦,也可以随意缩短这个丑陋的代码,我想有一个更短的方法来实现我的目标?
非常感谢您的帮助!
Oh and also feel free to shorten that ugly code, I guess there's a shorter way to achieve my goal? Thanks so much for your help!
推荐答案
最简洁:
$(document).ready(function() {
$("#Languages-spoken-and-understood-8").change(function() {
$("#li-2-21")[$(this).is(":checked") ? 'show' : 'hide']("fast")
}).change();
});
EDIT:从点击切换到变更活动
EDIT : switched from click to change event
这篇关于复选框显示隐藏字段 - 不工作onload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!