【问题标题】:Click Checkbox to disabled button单击复选框以禁用按钮
【发布时间】:2015-07-29 14:10:21
【问题描述】:

我想禁用发送表单的按钮,直到复选框被设置,我想用一个漂亮的简短 jQuery 代码来解决它。但是必须有一个错误,没有任何反应。有人有想法吗?

JS:

$(document).ready(function(){
$('#terms').keyup(function(){
    if($('#terms').is(':checked')){
          $('#btn').removeAttr('disabled');
    }else{
        $('#btn').attr('disabled');
}})}

HTML:

<input id="terms" type="checkbox" value="" name="terms">
    <input id="btn"   name="register" type="button" value="Register" disabled/>

【问题讨论】:

标签: javascript jquery forms


【解决方案1】:

其实很简单:

$('#terms').on("change", function() {
  $("#btn").prop("disabled", !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="terms" type="checkbox" value="" name="terms">
<input id="btn"   name="register" type="button" value="Register" disabled/>

!this.checked 是当前复选框状态的布尔值。
自然有一种 jQuery 方式:$(this).is(":not(:checked)"),但没有必要,因为您应该习惯于了解 this 环境和使用简单 vanilla JS read more 可用的 DOM 属性。

【讨论】:

  • 非常感谢!它有效,您将很快得到“正确答案”。需要等待几分钟。
【解决方案2】:

使用prop() 代替 attr:

例如

$('#btn').prop('disabled', true);

属性通常会影响 DOM 元素的动态状态,而无需 更改序列化的 HTML 属性。示例包括值 输入元素的属性,输入的禁用属性和 按钮,或复选框的选中属性。 .prop() 方法 应该用于设置禁用和检查而不是 .attr() 方法。 .val() 方法应该用于获取和设置 价值。

注意:您正在使用keyup 而不是change 事件作为复选框。

请注意,您的示例可以简化为只为开/关传递一个布尔表达式:

$(function(){
    $('#terms').change(function(){
        $('#btn').prop('disabled', !$(this).is(':checked'));
    });
});

【讨论】:

  • 您的代码无效。您缺少);$(this).is(':checked') 应该是:$(this).is(':not(:checked)') 或类似!$(this).is(':checked')
  • @RokoC.Buljan 谢谢。 “无效”对于拼写错误有点强烈,但已更正:)
  • strong,soft,随心所欲地调用它;)上面仍然会受到重创,因为您没有正确关闭 change 函数上的大括号 :) > 因此,是的,它坏了
  • @RokoC.Buljan 我确实喜欢为 OP 留下一些工作(已更正):)感谢您以 10 秒的优势击败我 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多