改进单选按钮的使用以启用/禁用表单字段
我有两个单选按钮和两个相应的表单字段。根据选择的单选按钮,一个表单字段将被禁用,而另一个表单字段将被启用。
我的代码可以运行,但我认为它可以改进。现在我有两个独立的进程。检查页面加载时选择了哪个单选按钮并禁用相应的字段。另一个在页面加载后响应用户的更改。我相信它可以简化,但我不知道如何简化。
$(document).ready(function() {
if ($("#element_link_link_type_internal").is(':checked')) {
$("#element_link_url").attr("disabled","disabled");
} else {
$("#element_link_page_id").attr("disabled","disabled");
}
});
$(document).ready(function() {
$("#element_link_link_type_internal").click(function(){
$("#element_link_page_id").attr("disabled","");
$("#element_link_url").attr("disabled","disabled");
}),
$("#element_link_link_type_external").click(function(){
$("#element_link_page_id").attr("disabled","disabled");
$("#element_link_url").attr("disabled","");
});
});
谢谢!
I have two radio buttons, and two corresponding form fields. Depending on which radio button is selected, one form field gets disabled and the other gets enabled.
My code works, but I think it can be improved. Right now I have two separate processes. One checks to see which radio button is selected when the page loads and disables the appropriate field. The other responds to changes by the user after the page has loaded. I believe it can be simplified but I don't know how.
$(document).ready(function() {
if ($("#element_link_link_type_internal").is(':checked')) {
$("#element_link_url").attr("disabled","disabled");
} else {
$("#element_link_page_id").attr("disabled","disabled");
}
});
$(document).ready(function() {
$("#element_link_link_type_internal").click(function(){
$("#element_link_page_id").attr("disabled","");
$("#element_link_url").attr("disabled","disabled");
}),
$("#element_link_link_type_external").click(function(){
$("#element_link_page_id").attr("disabled","disabled");
$("#element_link_url").attr("disabled","");
});
});
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在 onchange 处理程序中测试选中状态,并在页面加载时简单地调用 onchange 处理程序(我相信您应该使用它而不是 onclick)一次:
You can test the checked state within the onchange handler, and simply invoke the onchange handler (which I believe you should be using instead of onclick) once when the page loads:
这是未经测试的,基于您的评论/答案:
jQuery < 1.6:
jQuery >= 1.6
This is untested and based on your comments/answer:
jQuery < 1.6:
jQuery >= 1.6
@karim79,你的回答让我开始了,但当选择第二个单选按钮时它不起作用。仅当选择第一个单选按钮时它才起作用。
我想出了这个,看起来确实有效。不过,我欢迎任何人提供额外的改进。 JavaScript 让我大吃一惊。
@karim79, your answer got me started but it didn't work when the 2nd radio button was selected. It only worked when the 1st radio button was selected.
I came up with this, and it seems to do the trick. I'd welcome anyone to offer additional improvements though. JavaScript blows my mind.