Drupal.behaviors + jQuery: multiple buttons with the same name

While working for Mollom, I faced the problem of needing multiple buttons with the same name. In my case, this was an absolute necessity on an advanced multi-step form. Sounds super … easy, right? But HTML doesn't support this!

Thankfully, the combination of Drupal.behaviors and jQuery makes it easy to create a work-around! jQuery makes it easy to write the necessary code, Drupal.behaviors makes it trivial to ensure it keeps working even when new content has been added to the page (i.e. after an AHAH callback).

You would have a piece of Forms API code like this:

  1. $form['step1']['edit'] = array(
  2. '#type' => 'submit',
  3. '#value' => t('Edit step 1'),
  4. '#submit' => array('subscriptions_create_edit_step1'),
  5. '#attributes' => array('class' => 'edit-step-button'),
  6. );
  7.  
  8. // … more form definition code
  9.  
  10. $form['step4']['edit'] = array(
  11. '#type' => 'submit',
  12. '#value' => t('Edit step 4'),
  13. '#submit' => array('subscriptions_create_edit_step4'),
  14. '#attributes' => array('class' => 'edit-step-button'),
  15. );

As you can see, nothing remarkable about this, except for one thing: we've set the class attribute. This is used in our Drupal.behaviors method to detect which buttons this behavior should be applied to.

Next, add this piece of JavaScript code to your module's .js file:

  1. Drupal.behaviors.subscriptionsCreateFormEditStepButton = function() {
  2. $('.edit-step-button:not(.edit-step-button-processed)')
  3. .addClass('edit-step-button-processed').each(function () {
  4. var actualButtonName = $(this).val();
  5. $(this).val(Drupal.t('Edit'));
  6. $(this).click(function() {
  7. $(this).val(actualButtonName);
  8. });
  9. });
  10. };

This is a trivial piece of code: it overwrites the value attribute but restores it as soon as the button is pressed. But I think – or hope at least – that this will save 5 minutes of some people's time :)

Comments

Pingback

[...] Go to the author’s original blog: Drupal.behaviors + jQuery: multiple buttons with the same name [...]

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h2> <h3> <h4> <h5> <h6> <pre> <s>
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Lines and paragraphs break automatically.
  • Insert Flickr images: [flickr-photo:id=230452326,size=s] or [flickr-photoset:id=72157594262419167,size=m].
Syndicate content