1

I have a custom module built, and I would like to grey out and disable the submit form button if the textfield is empty. Can anyone help?

Here is the code for the textfield and the form button:

$form['ro-user-details']['nickname'] = array(
    '#type' => 'textfield', '#width' => 50,
    '#title' => t('Nickname'),
    '#default_value' => $ro_user->nickname,
    '#size' => 50,
    '#maxlength' => 200,
    '#required' => TRUE,
    );

    $form['ro-user-details']['change_nickname'] = array('#type' => 'submit', '#value' => t('Change Nickname'));

1 Answer 1

1

Obviously you will want to do this with some jQuery...And of course there is more than one way to do this, but:

$(function(){
      //Set button disabled
      $("input[type='submit']").attr("disabled", "disabled");

      //Append a change event listener to your input
      $("input[name='nickname']").change(function(){

            if($(this).val().length > 0) {
              $("input[type='submit']").removeAttr("disabled");  
            }                            
      });

      // You could then trigger the a change event on load just to check
      $("input[name='nickname'").trigger('change');
});

That should be the gist of it. Of course you would want to change your "name" value to whatever your input name is.

2
  • If you want to add custom JS, then you should use behaviors (look towards the bottom) to ensure that the JS is run on all markup (even stuff that gets AJAXed down after the initial page load). Note that a non-JS method would be to use the states API.
    – Andy
    Commented Aug 3, 2012 at 8:20
  • Be aware that the onclick event for the button will still, so if the button has javascript behavior, it will probably trigger anyways.
    – dysrama
    Commented Aug 3, 2012 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.