关于javascript:jQuery禁用/启用提交按钮

jQuery disable/enable submit button

我有这个HTML:

1
2
<input type="text" name="textField" />
<input type="submit" value="send" />

我该怎么做这样的事情:

  • 当文本字段为空时,应禁用提交(禁用="禁用")。
  • 在文本字段中键入内容以删除已禁用的属性时。
  • 如果文本字段再次变为空(文本被删除),则应再次禁用提交按钮。

我试过这样的事情:

1
2
3
4
5
6
7
8
$(document).ready(function(){
    $('input[type="submit"]').attr('disabled','disabled');
    $('input[type="text"]').change(function(){
        if($(this).val != ''){
            $('input[type="submit"]').removeAttr('disabled');
        }
    });
});

......但它不起作用。 有任何想法吗?


问题是只有当焦点远离输入时才会触发更改事件(例如,有人点击输入或标签输出)。尝试使用keyup:

1
2
3
4
5
6
7
8
$(document).ready(function() {
     $(':input[type="submit"]').prop('disabled', true);
     $('input[type="text"]').keyup(function() {
        if($(this).val() != '') {
           $(':input[type="submit"]').prop('disabled', false);
        }
     });
 });


1
2
3
4
5
6
7
8
9
10
11
12
13
$(function() {
  $(":text").keypress(check_submit).each(function() {
    check_submit();
  });
});

function check_submit() {
  if ($(this).val().length == 0) {
    $(":submit").attr("disabled", true);
  } else {
    $(":submit").removeAttr("disabled");
  }
}


这个问题已经有2年了,但它仍然是一个很好的问题,这是Google的第一个结果...但是所有现有的答案都建议设置和删除HTML属性(removeAttr("disabled"))"disabled",这不是正确的方法。关于属性与属性存在很多混淆。

HTML

标记中中的"禁??用"被W3C称为布尔属性。

HTML与DOM

引用:

A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.

https://stackoverflow.com/a/7572855/664132

JQuery的

有关:

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property...

相关:

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.

1
$("input" ).prop("disabled", false );

摘要

要[...]更改DOM属性,例如表单元素的禁用状态,请使用.prop()方法。

(http://api.jquery.com/attr/)

关于更改部分问题的禁用:有一个名为"input"的事件,但浏览器支持有限,并且它不是jQuery事件,因此jQuery不会使它工作。 change事件可靠地工作,但在元素失去焦点时触发。所以可以将两者结合起来(有些人也会听取密钥和粘贴)。

这是一段未经测试的代码,用于表明我的意思:

1
2
3
4
5
6
7
$(document).ready(function() {
    var $submit = $('input[type="submit"]');
    $submit.prop('disabled', true);
    $('input[type="text"]').on('input change', function() { //'input change keyup paste'
        $submit.prop('disabled', !$(this).val().length);
    });
});


要删除已禁用的属性,

1
 $("#elementID").removeAttr('disabled');

并添加禁用的属性使用,

1
$("#elementID").prop("disabled", true);

请享用 :)


或者对于我们不喜欢为每件小事使用jQ:

1
document.getElementById("submitButtonId").disabled = true;


eric,当用户输入文本然后删除所有文本时,您的代码似乎对我不起作用。如果有人遇到同样的问题我创建了另一个版本。在这里你去的人:

1
2
3
4
5
6
7
8
9
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').keyup(function(){
    if($('input[type="text"]').val() ==""){
        $('input[type="submit"]').attr('disabled','disabled');
    }
    else{
        $('input[type="submit"]').removeAttr('disabled');
    }
})

它会像这样工作:

1
2
3
4
5
6
7
$('input[type="email"]').keyup(function() {
    if ($(this).val() != '') {
        $(':button[type="submit"]').prop('disabled', false);
    } else {
        $(':button[type="submit"]').prop('disabled', true);
    }
});

确保HTML中存在"已禁用"属性


这是文件输入字段的解决方案。

要在未选择文件时禁用文件字段的提交按钮,请在用户选择要上载的文件后启用:

1
2
3
4
5
6
$(document).ready(function(){
    $("#submitButtonId").attr("disabled","disabled");
    $("#fileFieldId").change(function(){
        $("#submitButtonId").removeAttr("disabled");
    });
});

HTML:

1
<%= form_tag your_method_path, :multipart => true do %><%= file_field_tag :file, :accept =>"text/csv", :id =>"fileFieldId" %><%= submit_tag"Upload", :id =>"submitButtonId" %><% end %>

你也可以使用这样的东西:

1
2
3
4
5
6
7
8
9
10
$(document).ready(function() {
    $('input[type="submit"]').attr('disabled', true);
    $('input[type="text"]').on('keyup',function() {
        if($(this).val() != '') {
            $('input[type="submit"]').attr('disabled' , false);
        }else{
            $('input[type="submit"]').attr('disabled' , true);
        }
    });
});

这是Live的例子


对于表单登录:

1
2
3
4
5
<form method="post" action="/login">
    <input type="text" id="email" name="email" size="35" maxlength="40" placeholder="Email" />
    <input type="password" id="password" name="password" size="15" maxlength="20" placeholder="Password"/>
    <input type="submit" id="send" value="Send">
</form>

使用Javascript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function() {    
    $('#send').prop('disabled', true);

    $('#email, #password').keyup(function(){

        if ($('#password').val() != '' && $('#email').val() != '')
        {
            $('#send').prop('disabled', false);
        }
        else
        {
            $('#send').prop('disabled', true);
        }
    });
});

如果按钮本身是一个jQuery样式的按钮(带.button()),则需要刷新按钮的状态,以便在删除/添加disabled属性后添加/删除正确的类。

1
$(".selector" ).button("refresh" );


上面的答案也没有涉及检查基于菜单的剪切/粘贴事件。下面是我用来做两者的代码。请注意,操作实际上会在超时时发生,因为切换和过去事件实际上会在更改发生之前触发,因此超时会给出一点时间。

1
2
3
4
5
6
$(".your-input-item" ).bind('keyup cut paste',function() {
    var ctl = $(this);
    setTimeout(function() {
        $('.your-submit-button').prop( 'disabled', $(ctl).val() == '');
    }, 100);
});

我们可以简单地使用if&else。如果您的输入为空,我们可以拥有

1
2
3
  if($(#name).val() != '') {
                $('input[type="submit"]').attr('disabled' , false);
            }

否则我们可以将false改为true


香草JS解决方案。 它适用于整个形式,而不仅仅是一个输入。

有问题选择JavaScript标记。

HTML表格:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var form = document.querySelector('form')
    var inputs = form.querySelectorAll('input')
    var required_inputs = form.querySelectorAll('input[required]')
    var register = document.querySelector('input[type="submit"]')
    form.addEventListener('keyup', function(e) {
        var disabled = false
        inputs.forEach(function(input, index) {
            if (input.value === '' || !input.value.replace(/\s/g, '').length) {
                disabled = true
            }
        })
        if (disabled) {
            register.setAttribute('disabled', 'disabled')
        } else {
            register.removeAttribute('disabled')
        }
    })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<form action="/signup">
       
            <label for="username">User Name</label>
            <input type="text" name="username" required/>
       
       
            <label for="password">Password</label>
            <input type="password" name="password" />
       
       
            <label for="r_password">Retype Password</label>
            <input type="password" name="r_password" />
       
       
            <label for="email">Email</label>
            <input type="text" name="email" />
       
        <input type="submit" value="Signup" disabled="disabled" />
    </form>

一些解释:

在此代码中,我们在html表单上添加keyup事件,并在每个按键上检查所有输入字段。 如果我们至少有一个输入字段为空或仅包含空格字符,那么我们将true值分配给disabled变量并禁用submit按钮。

如果您需要禁用提交按钮,直到填写所有必需的输入字段 - 替换:

1
inputs.forEach(function(input, index) {

有:

1
required_inputs.forEach(function(input, index) {

其中required_inputs已被声明为仅包含必需输入字段的数组。


请参阅以下代码以启用或禁用"提交"按钮

If Name and City fields has value then only Submit button will be enabled.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  $(document).ready(function() {
    $(':input[type="submit"]').prop('disabled', true);

    $('#Name').keyup(function() {
      ToggleButton();
    });
    $('#City').keyup(function() {
      ToggleButton();
    });

  });

function ToggleButton() {
  if (($('#Name').val() != '') && ($('#City').val() != '')) {
    $(':input[type="submit"]').prop('disabled', false);
    return true;
  } else {
    $(':input[type="submit"]').prop('disabled', true);
    return false;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<form method="post">

 
   
      Getting started
      <fieldset>
        <label class="control-label text-danger">Name</label>
        <input type="text" id="Name" name="Name" class="form-control" />
        <label class="control-label">Address</label>
        <input type="text" id="Address" name="Address" class="form-control" />
        <label class="control-label text-danger">City</label>
        <input type="text" id="City" name="City" class="form-control" />
        <label class="control-label">Pin</label>
        <input type="text" id="Pin" name="Pin" class="form-control" />
        <input type="submit" value="send" class="btn btn-success" />
      </fieldset>
   
 
</form>


禁用:$('input[type="submit"]').prop('disabled', true);

启用:$('input[type="submit"]').removeAttr('disabled');

以上启用代码比以下更准确:

1
$('input[type="submit"]').removeAttr('disabled');

您可以使用这两种方法。


我必须努力使这适合我的用例。

我有一个表单,其中所有字段在提交之前必须具有值。

这是我做的:

1
2
3
4
5
6
7
8
9
10
11
12
13
  $(document).ready(function() {
       $('#form_id button[type="submit"]').prop('disabled', true);

       $('#form_id input, #form_id select').keyup(function() {
          var disable = false;

          $('#form_id input, #form_id select').each(function() {
            if($(this).val() == '') { disable = true };
          });

          $('#form_id button[type="submit"]').prop('disabled', disable);
       });
  });

感谢大家的回答。


从我的项目中查看此片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 $("input[type="submit"]","#letter-form").on("click",
        function(e) {
             e.preventDefault();


$.post($("#letter-form").attr('action'), $("#letter-form").serialize(),
                 function(response) {// your response from form submit
                    if (response.result === 'Redirect') {
                        window.location = response.url;
                    } else {
                        Message(response.saveChangesResult, response.operation, response.data);
                    }
});
$(this).attr('disabled', 'disabled'); //this is what you want

so just disabled the button after your operation executed

$(this).attr('disabled', 'disabled');


提供Al类型的溶液。所以我想尝试不同的解决方案。如果在输入字段中添加id属性,则更简单。

1
2
<input type="text" name="textField" id="textField"/>
<input type="submit" value="send" id="submitYesNo"/>

现在这是你的jQuery

1
2
3
4
5
6
$("#textField").change(function(){
  if($("#textField").val()=="")
    $("#submitYesNo").prop('disabled', true)
  else
    $("#submitYesNo").prop('disabled', false)
});


我希望下面的代码可以帮助别人.. !!!:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
jQuery(document).ready(function(){

    jQuery("input[type=submit]").prop('disabled', true);

    jQuery("input[name=textField]").focusin(function(){
        jQuery("input[type=submit]").prop('disabled', false);
    });

    jQuery("input[name=textField]").focusout(function(){
        var checkvalue = jQuery(this).val();
        if(checkvalue!=""){
            jQuery("input[type=submit]").prop('disabled', false);
        }
        else{
            jQuery("input[type=submit]").prop('disabled', true);
        }
    });

}); /*DOC END*/