samedi 11 juin 2016

jquery to disable buttons on submit/click in forms and links


In my rails app I have buttons that submit information to the server. Some buttons are part of a form and some are not. I'm looking for a way to apply my jquery, which disables the buttons after click, to both.

Here is my current jquery:

  $('.btn-disabler').on('click', function() {
    $(this).append("<i class='fa fa-spinner fa-pulse btn-loader'>").disable(true);
    $(this).find('.btn-label').addClass('invisible');
  });

This code adds an icon disables the button and makes the text invisible. I've extended the disable function to work on anchor tags as explained here http://stackoverflow.com/a/16788240/4584963

An example link:

<a class="btn btn-success btn-disabler" rel="nofollow" data-method="post" href="/approve?id=10">
  <span class="btn-label">Approve</span>
</a>

An example form:

<form class="simple_form well" novalidate="novalidate" id="new_user" action="/" accept-charset="UTF-8" method="post">
      <div class="form-group">
        <input class="string optional form-control" placeholder="First name" type="text" name="user[first_name]" id="user_first_name">
      </div>
      <div class="form-group">
        <input class="string optional form-control" placeholder="Last name" type="text" name="user[last_name]" id="user_last_name">
      </div>
      <div class="form-group">
        <input class="string email optional form-control" placeholder="Email" type="email" name="user[email]" id="user_email">
      </div>
      <div class="form-group">
        <input class="password optional form-control" placeholder="Password" type="password" name="user[password]" id="user_password">
      </div>                
      <div class="form-groups">
        <input class="password optional form-control" placeholder="Retype password" type="password" name="user[password_confirmation]" id="user_password_confirmation">
      </div>
      <button name="button" type="submit" class="btn btn btn-primary btn-disabler">
        <span class="btn-label">Submit</span>
      </button>
</form>

My jquery above does not work for the form. In the form on click, the button changes but there is no submission. To get the jquery to work for the form I need to change it to this:

  $('.signup-form').on('submit', function() {
    $(this).find('.btn-disabler').append("<i class='fa fa-spinner fa-pulse btn-loader'>").disable(true);
    $(this).find('.btn-label').addClass('invisible');
  });

How can I consolidate this to apply to both links and form submit buttons? Seems like my problem stems from links need the click event and the form needs the submit event.


Aucun commentaire:

Enregistrer un commentaire