如何使用 JQuery 在勾选复选框后激活输入字段?
我编写了这段代码,但它似乎不起作用,请参见下文:
$('#Reserve, #BuyItNowPrice, #featureplate').attr('disabled','disabled');
$('.fake-fieldset .fake-input').css({'background-color':'#e1e1e1'});
$('.enable').click(function(){
if($('.enable:checked')){
$(this).closest('input').removeAttr('disabled');
}
else{
$(this).closest('input').attr('disabled','disabled');
}
});
此 HTML 结构在我的代码中重复了 3 次,请参见下文
<strong><input type="checkbox" class="enable" /> Specify Buy It Now Price</strong>
<div class="fake-fieldset">
<div class="fake-input">
<span>£ </span>
<input type="text" id="BuyItNowPrice" name="BuyItNowPrice" value="" />
</div>
</div>
我希望发生的是当我检查 .enable
时最接近的输入应该变为活动状态,以便用户可以键入一个值
任何帮助将不胜感激,谢谢
I have this code I wrote but it doesnt seem to be working, see below:
$('#Reserve, #BuyItNowPrice, #featureplate').attr('disabled','disabled');
$('.fake-fieldset .fake-input').css({'background-color':'#e1e1e1'});
$('.enable').click(function(){
if($('.enable:checked')){
$(this).closest('input').removeAttr('disabled');
}
else{
$(this).closest('input').attr('disabled','disabled');
}
});
This HTML structure is repeated 3 times in my code, see below
<strong><input type="checkbox" class="enable" /> Specify Buy It Now Price</strong>
<div class="fake-fieldset">
<div class="fake-input">
<span>£ </span>
<input type="text" id="BuyItNowPrice" name="BuyItNowPrice" value="" />
</div>
</div>
What I'd like to happen is when I check .enable
the closest input should become active so the user can type a value
Any help would be greatly appreciated, Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
需要改变的一件事:我认为你不能这样做,
因为选择器总是返回一个 jQuery 对象(而不是 true 或 false);相反,请尝试
第二,由于
closest
正在寻找祖先,因此您需要一种更好的方法来将复选框与相关的输入
连接起来;也许将它们都放入包装 div 中?然后您可以转到父级(包装器)并从那里进行查找。One thing to change: I don't think you can do
as a selector always returns a jQuery object (rather than true or false); instead try
Second, since
closest
is looking for an ancestor, you need a better way to connect the checkbox with the relatedinput
; maybe put them both into a wrapper div? Then you can go up to the parent (the wrapper) and do a find from there.Jquery 的 closest 查找您要更改的
input
的祖先元素不是。您可能需要稍微更改一下 HTML 才能使其正常工作。一个建议是创建一个父元素来包装这两个元素,并向第二个输入添加一个类。像这样的:
然后你可以找到第二个输入,如下所示:
Jquery's closest looks for an ancestor element which the
input
you are trying to change is not.You probably need to change your HTML a bit to make this work. One suggestion is to create a parent element to wrap both elements and add a class to the 2nd input. Something like this:
Then you can find that 2nd input like this: