Enabling submit button if text entered

Published on January 13, 2009 and tagged with jquery  refactoring

While looking at some jQuery code I wrote a while ago I noticed the following snippet:

$('#username').keyup(function() {
    if ($('#username').val() != '') {
        $('#submit').removeAttr('disabled');
    } else {
        $('#submit').attr('disabled', 'disabled');
    }
});

It ensures that the submit button is only enabled if the “username” input field is not empty (you can see such a behavior on twitter for example).

However, the snippet from above can be rewritten in a shorter and more elegant way:

$('#username').keyup(function() {
    $('#submit').attr('disabled', !$('#username').val()); 
});

Maybe this is helpful for someone out there ;-)

4 comments baked

  • Eelco Wiersma January 14, 2009 at 00:55

    Don’t forget to add the following, in order to disable the submit button once the document is loaded:

    $(function() {
        $('#submit').attr('disabled', 'disabled');
    })

    Instead of hardcoding the disable tag in your html.

  • Fenrir January 14, 2009 at 05:52

    What if username was filled by browser itself or pasted by mouse only?

  • Xr January 14, 2009 at 09:40

    Fenrir: for mouse pasting, you could use the onchange event, but it won’t be triggered before a focus change (the submit will not magically be enabled when something is entered).

    As for the browser auto-fill, you could probably replace Eelco’s code with

    $(function() {
        $('#submit').attr('disabled', !$('#username').val()); 
    })

    Hoping the browser fills fields before triggering the onload event.

    On a sidenote, this does not generate valid XHTML and I’m surprised this works since even the HTML 4.01 specifies that the element will be disabled if the attribute is set (not only if set to a non-null string). In regards to that, the first code was better but I didn’t test any of them.

  • cakebaker January 15, 2009 at 18:16

    @all: Thanks for your comments!

    @Eelco: Yes, if you don’t want to disable the button in the html you have to use the snippet you provided.

    @Xr: Hm, I think this is handled automatically by jQuery. At least if I look at the DOM with FireBug, the “disabled” attribute disappears when the button is enabled by the script (and reappears when the script disables the button).

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License