Enabling submit button if text entered

Published on 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 ;-)

6 comments baked

  • Eelco Wiersma

    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

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

  • Xr

    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

    @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).

  • Awesome jQuery snippets to work with forms « Blog de xkortazar
  • Enable submit button if text entered with jQuery

    [...] : Source0var dd_offset_from_content = 55; var dd_top_offset_from_content = 0;   0 [...]

Bake a comment




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

© daniel hofstetter. Licensed under a Creative Commons License