取消选中/选中复选框时尝试启用/禁用输入文本 [英] Trying to enable/disable an input text when a chekbox is unchecked/checked

查看:73
本文介绍了取消选中/选中复选框时尝试启用/禁用输入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在选中/取消选中复选框时,我正在尝试启用/禁用输入文本

I'm trying to enable/diable an input text when a chekbox is checked/unchecked

我已经在下面尝试过了,但是没有用..

I have tried this below but it doesn't work..

  $('#checkbox').change(function(){


    if($('#name').attr('disabled') == 'true')
      $('#name').attr('disabled', 'false');
    else
      $('#name').attr('disabled', 'true');

  });

有帮助吗?

致谢

哈维

推荐答案

在两种情况下,您都将"disabled"属性设置为true.尝试以下方法:

You're setting the "disabled" attribute to true in both cases. Try this instead:

if($('#name').attr('disabled'))
  $('#name').attr('disabled', false);
else
  $('#name').attr('disabled', true);

或更简单地说:

 $('#name').attr('disabled', !$('#name').attr('disabled'));

您使用的字符串— "true"和"false"—都是JavaScript的true值.它们是非空字符串,这很重要.当使用实常数truefalse时,您将获得所需的结果.

The strings you used — "true" and "false" — are both true values to JavaScript. They're non-empty strings, and that's all that matters. When you use the real constants true and false, you get what you intended.

使用禁用"作为属性的true值的常见做法是一种愚蠢的迷信,实际上是没有根据的.当然,它确实起作用,因为"disabled"也是一个非空字符串,因此它是true.如果需要,可以将null用作false值,也可以使用数字零.

The common practice of using "disabled" as the true value for the attribute is a silly superstition that has no basis in fact. It does work, of course, because "disabled" is also a non-empty string, and so it's true. You could use null for the false value if you wanted to, or a numeric zero.

edit —根据有用的注释修复了if语句.所需要做的就是检查属性的真实性.

edit — fixed the if statement as per the helpful comment. All that's necessary is to check the truthiness of the attribute.

这篇关于取消选中/选中复选框时尝试启用/禁用输入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆