0

我对 JQuery 很陌生:我有点困惑,但询问比其他方法更好:

我正在尝试禁用按钮,但在字段/文本框中有内容时启用它。这只是实验性的,只是在这里弄湿我的脚。

或者,我可以禁用按钮windows load或直接在表单元素上应用属性。

$(document).ready(function() {

 $('#btnSubmit').attr('disabled', true);

$('#myForm :input').blur(function(){
    if($('#myField').val() == '')
    {
        $('#btnSubmit').attr('disabled', true);
    }
    else
    {
        $('#btnSubmit').attr('disabled', false);
    }
});
});

问题是在我输入一个值并离开该字段后,该按钮已启用,但一旦我单击该按钮,它就会再次被禁用:

我错过了什么?

谢谢我的朋友。

4

5 回答 5

2

这是因为button也被视为输入字段。

尝试

$('#myForm :input:not(:button)').

演示:小提琴

也使用.prop()而不是.attr()设置禁用状态

于 2013-06-24T09:37:44.680 回答
0

你可以试试这个,onkeyup检查文本框是否为空是禁用按钮,否则启用按钮。

HTML:

 <form id="myForm">
       <input id="myField" type="text"/>
       <input id="btnSubmit" value="hi" type="button"/>

  </form>

jQuery:

$(document).ready(function() {
        //Load with button disabled,since the value of the textbox will be empty initially
        $('#btnSubmit').attr('disabled', true);
        //onkeyup check if the textbox is empty or not
        $('#myForm input[type="text"]').keyup(function(){
           if($('#myField').val() == '')
             {
               $('#btnSubmit').prop('disabled', true);
             }
            else
            {
               $('#btnSubmit').prop('disabled', false);
            }
           });
          });

$(document).ready(function() {
     $('#btnSubmit').prop('disabled', true);
    $('#myForm input[type="text"]').keyup(function(){
       if($('#myField').val() == '')
         {             
           $('#btnSubmit').prop('disabled', true);         
         }
        else
        {
           $('#btnSubmit').prop('disabled', false);
        }
       }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
         <input id="myField" type="text"/>
         <input id="btnSubmit" value="hi" type="button"/>

      </form>

于 2013-06-24T10:01:00.827 回答
0

试试这个,应该可以

HTML 示例

<input type = "text" id = "txt1">
<button class = "btnSubmit">Submit</button>

和jQuery

$(".btnSubmit").attr("disabled", "disabled");
$("#txt1").keyup(function() {
    if(jQuery.trim($(this).val()) != '') {
       $('.btnSubmit').removeAttr('disabled');
    }
});
于 2013-06-24T09:45:32.723 回答
0
$('#myForm:input').on('keyup' , function() {

    if($.trim($('#myField').val()).length > 0){
       $('#btnSubmit').prop('disabled', false);
    }
    else {
       $('#btnSubmit').prop('disabled', true);
    }

});

*这会奏效。请尝试*

于 2013-06-24T09:53:11.080 回答
0

尝试使用这个:

$('#btnSubmit').attr('disabled', 'disabled'); // to disable buttons
$('#btnSubmit').removeAttr('disabled'); // to enable them
于 2013-06-24T09:38:24.043 回答