jQuery复选框,用于启用/禁用文本输入并添加/删除默认值 [英] jQuery checkbox to enable/disable text input and add/remove default value

查看:127
本文介绍了jQuery复选框,用于启用/禁用文本输入并添加/删除默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个小的可重用函数,当选中该函数时,将禁用文本字段并插入默认值160,当取消选中时,启用该字段并删除该值。我大部分时间都已完成,但是未完成的部分让我失望。

I am trying to create a small reusable function that will, when checked, disable a text field and insert a default value of '160', and when unchecked, enable the field and remove the value. I have it mostly finished but the unchecking part is throwing me off.

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


   if ($('#chkIsTeamLead').checked = true){
      $('#txtNumHours').val('160').attr('disabled', 'disabled');
      console.log('checked');
   }

  if ($('#chkIsTeamLead').checked = false){
     $('#txtNumHours').val('').removeAttr('disabled');
     console.log('unchecked');
   }

});

我将它设置为可重复使用的函数,并且传递了参数,但这给了我更多麻烦,我希望参数是复选框,目标和值,最好是
链接到我当前的代码: http ://codepen.io/AlexBezuska/pen/bwgsA
感谢您提供的任何帮助!

I had it setup as a reusable function with arguments passed to it but that was giving me more trouble, I would like the arguments to be checkbox, target, and value preferably link to my current code: http://codepen.io/AlexBezuska/pen/bwgsA Thanks for any help you can provide!

推荐答案

工作jsFiddle演示


  1. 使用 .is(':checked')

  2. 您必须将两个值与<$进行比较c $ c> == 。

  3. 当您使用禁用等属性时,最好是使用 .prop()方法而不是 .attr()

  1. Use .is(':checked').
  2. You must compare two values with ==.
  3. When you are working with attribute like disabled, it's better to use .prop() method instead of .attr().







$('#chkIsTeamLead').change(function(){
    if ($('#chkIsTeamLead').is(':checked') == true){
        $('#txtNumHours').val('160').prop('disabled', true);
        console.log('checked');
    } else {
        $('#txtNumHours').val('').prop('disabled', false);
        console.log('unchecked');
    }
});






参考文献:


References:

  • .attr() - jQuery API Documentation
  • .prop() - jQuery API Documentation
  • .is() - jQuery API Documentation

这篇关于jQuery复选框,用于启用/禁用文本输入并添加/删除默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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