[英]I dont know whats wrong with this simple javascript code, I have checked this over and over again but does not work
[英]Whats wrong with this code? .checked is probably the one i am not using correctly
我有一个简单的HTML表单。 这是登录页面时遇到的麻烦,两个单选按钮,一个忘记密码,另一个忘记用户名。 当用户单击一个单选按钮时,该选项下方会出现一个小表格,然后他可以继续进行操作。 我刚刚写了用户名部分。 并为此编写了一个小函数,但实际上并不能完全正常工作。
我已经检查了jquery选择器,#usernamedrop的形式确实隐藏了,但是if语句不能正常工作。
$(document).ready(function(e){
$("#usernamedrop").hide();
$("#usernameradio").change(function(e){
if($("#usernameradio").checked){
$("#usernamedrop").show();
}else {
$("#usernamedrop").hide();
}
});
});
html如下:
<body>
<div id="logindiv">
<h1>What is the problem?</h1>
<div>
<div class="formentry">
<input type="radio" name="troublekind" id="usernameradio" value="username">
<label for="usernameradio">I forgot my username</label>
</div>
<div class="formentry">
<input type="radio" name="troublekind" id="passwordradio" value="password">
<label for="passwordradio">I forgot my password</label>
</div>
</div>
<form id="usernamedrop">
<h2>Please Enter</h2>
<div class="formentry">
<label for="dateofbirth">Date Of Birth</label><input type="date" name="dateofbirth" id="dateofbirth">
</div>
<div class="formentry">
<label for="placeofbirth">Place Of Birth</label><input type="text" name="placeofbirth" id="placeofbirth">
</div>
<input type="submit" name="submitusernamedrop" value="Submit">
</form>
</div>
您正在混合Vanialla JS和jQuery。 $("#usernameradio")
是一个jQuery对象,没有checked
属性。
您可以使用多种方法来检查属性:
this.checked;
,简单而最佳的方法 $(this).is(':checked');
$(this).prop('checked');
采用
$("#usernameradio").change(function(e){
if(this.checked){
$("#usernamedrop").show();
}else {
$("#usernamedrop").hide();
}
});
尝试
$("#usernameradio").change(function(e){
if($(this).prop('checked')){
$("#usernamedrop").show();
}else {
$("#usernamedrop").hide();
}
});
我使用.prop检查属性是否具有值prop('checked')
如果检查了单选,则返回true。
checked
的属性位于DOM元素上,而不是jQuery集合上。 this
是指元素,因此您可以执行this.checked
或$(this).prop('checked')
。 最后,您还可以使用toggle
,它需要一个“ switch”来隐藏或显示元素:
$("#usernameradio").change(function(){
$("#usernamedrop").toggle(!this.checked);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.