Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

javascript - jQuery禁用/启用提交按钮(jQuery disable/enable submit button)

I have this HTML:

(我有这个HTML:)

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

How can I do something like this:

(我该如何做这样的事情:)

  • When the text field is empty the submit should be disabled (disabled="disabled").

    (当文本字段为空时,应禁用提交(disabled =“ disabled”)。)

  • When something is typed in the text field to remove the disabled attribute.

    (在文本字段中键入内容以删除禁用的属性时。)

  • If the text field becomes empty again(the text is deleted) the submit button should be disabled again.

    (如果文本字段再次变为空(删除了文本),则应再次禁用提交按钮。)

I tried something like this:

(我尝试过这样的事情:)

$(document).ready(function(){
    $('input[type="submit"]').attr('disabled','disabled');
    $('input[type="text"]').change(function(){
        if($(this).val != ''){
            $('input[type="submit"]').removeAttr('disabled');
        }
    });
});

…but it doesn't work.

(…但这不起作用。)

Any ideas?

(有任何想法吗?)

  ask by kmunky translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that the change event fires only when focus is moved away from the input (eg someone clicks off the input or tabs out of it).

(问题在于,仅当焦点从输入移开时,更改事件才会触发(例如,有人单击了输入或将选项卡移出了输入)。)

Try using keyup instead:

(尝试改用keyup:)

$(document).ready(function() {
     $(':input[type="submit"]').prop('disabled', true);
     $('input[type="text"]').keyup(function() {
        if($(this).val() != '') {
           $(':input[type="submit"]').prop('disabled', false);
        }
     });
 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...