[英]How do I show an input field if a radio button is checked using jquery
I have a radio button called "other," and when checked, I want a input field called "other-text" to show up. 我有一个名为“其他”的单选按钮,当选中该按钮时,我希望显示一个名为“其他文本”的输入字段。 It's fairly simple, but I've been failing all morning.
这很简单,但是我整个上午都在失败。
<input name="ocalls" type="radio" name="other" id="other-radio" value="Yes"><b>Other</b><br />
<input type="text" name="other-text" id="other-text" style="display:none" />
Here is my javascript: 这是我的JavaScript:
jQuery(function(){
jQuery("input[name=other]").change(function(){
if ($(this).val() == "Yes") {
jQuery("#other-text").show()
}
else {
jQuery("#other-text").hide();
}
});
});
JSFiddle of the failure. JSFiddle的失败。 http://jsfiddle.net/Wpt3Y/532/
http://jsfiddle.net/Wpt3Y/532/
I suggest to go this way. 我建议走这种方式。 Tried to use prop() but realised you use old version of
jquery
尝试使用prop(),但意识到您使用的是旧版本的
jquery
jQuery("input:radio[name='ocalls']").change(function(){
if ($(this).attr("checked") == true) {
jQuery("#other-text").show();
}
else {
jQuery("#other-text").hide();
}
});
Instead you can use checkbox: 相反,您可以使用复选框:
html html
<input name="ocalls" type="checkbox" name="other" id="other-radio" value="Yes"><b>Other</b><br />
<input type="text" name="other-text" id="other-text" style="display:none" />
js js
jQuery("input:checkbox[name='ocalls']").change(function(){
if ($(this).attr("checked") == true) {
jQuery("#other-text").show();
}
else {
jQuery("#other-text").hide();
}
});
这有效
jQuery("#other-radio").change(function(){...
Just updated your jsfiddle: http://jsfiddle.net/Wpt3Y/539/ 刚刚更新了jsfiddle: http : //jsfiddle.net/Wpt3Y/539/
<pre><input type="radio" name="other" id="other-radio" value="Yes"><b>Other</b></pre>
Your code works, you simply mistyped your radio input, it had two name attributes. 您的代码有效,您仅键入了错误的单选输入,它具有两个名称属性。
<form>
<input name="ocalls" type="radio" name="other" id="other-radio" value="Yes">
<b>Other</b><br />
</input>
<input type="text" name="other-text" id="other-text" style="display: none;" />
</form>
jQuery(function(){
jQuery("#other-radio").change(function(){
if ($(this).val() == "Yes") {
jQuery("#other-text").show()
}
else {
jQuery("#other-text").hide();
}
});
});
Try this. 尝试这个。
If you want that toggle effect you can use this code with the checkbox. 如果您想要那种切换效果,可以将此代码与复选框一起使用。
jQuery(function(){
jQuery("input[name=ocalls]").change(function(){
if($(this).attr("checked"))
{
$("#other-text").show();
}
else
{
$("#other-text").hide();
}
});
});
Your code is not working because you have name
attribute twice in radio
button. 您的代码不起作用,因为您在
radio
按钮中两次拥有name
属性。
use this: 用这个:
<input type="radio" name="other" id="other-radio" value="Yes">
remove name="ocalls"
attribute. 删除
name="ocalls"
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.