复选框上的jQuery验证单击禁用TextBox?

时间:2011-10-19 21:15:57

标签: javascript jquery

您好我正在努力让这个JavaScript为我工作。

任何人都可以帮助我。

当用户点击复选框时,下一个文本框应该禁用, 如果未选中则启用。

当我在IE9开发人员工具中调试脚本时,

选择器工作正常。

函数正常运行。

<input id="RefillNeeded10" name="RefillasNeeded" type="checkbox" value="true">
<input type="text" size="5" id="RefillTB10," name="Refills">

$('input[type="checkbox"][name^="RefillasNeeded"]').click(function () {
var num = $(this).attr('id').replace("RefillNeeded", "");
if ($('input[type="checkbox"][id="RefillNeeded' + num + '"]').attr("checked")) {
  $('input[type="text"][id="RefillTB' + num + '"]').attr("disabled", true);
                   }
  else {
  $('input[type="text"][id="RefillTB' + num + '"]').attr("disabled", false);
   }
 });

$('input[type="text"][id="RefillTB' + num + '"]').attr("disabled", true); 这不是创建属性disable。

为方便起见,我列出了here

3 个答案:

答案 0 :(得分:1)

您的选择器与任何元素都不匹配。您的HTML中似乎有拼写错误 - 文本框的,中有一个尾随id。从您的id属性中删除逗号,它应该工作。 http://jsfiddle.net/gilly3/KJVCa/13/


顺便说一句,你不需要那么大的长选择器来获取复选框并测试它是否被选中。您已将其引用为this。您可以查看其checked属性:

if (this.checked)

虽然我们正在努力,但为什么不真正简化事情。您不需要解析id,只需获取下一个元素(假设您的文本框始终跟随您的复选框)。您不需要if,只需直接使用布尔值即可。您的代码可以缩小到这个:

$("input[type=checkbox][name^=RefillasNeeded]").click(function () {
    $(this).next().attr("disabled", this.checked);
});

请在此处查看:http://jsfiddle.net/gilly3/KJVCa/15/

答案 1 :(得分:0)

同样对于我必须改变的javascript

$('input[type="checkbox"][id="RefillNeeded' + num + '"]').attr("checked")

$('input[type="checkbox"][id="RefillNeeded' + num + '"]').is(":checked")

让它发挥作用。

答案 2 :(得分:-1)

更改

$('input[type="text"][id="RefillTB' + num + '"]').attr("disabled", "disabled");

$('input[type="text"][id="RefillTB' + num + '"]').attr("disabled", "");

$('input[type="text"]["#RefillTB' + num + '"]').attr("disabled", "disabled");

$('input[type="text"]["#RefillTB' + num + '"]').removeAttr("disabled");

分别