DRY jQuery for RESTful PUT/DELETE links

Posted by Aupajo on Stack Overflow See other posts from Stack Overflow or by Aupajo
Published on 2009-05-27T04:41:28Z Indexed on 2010/06/15 5:32 UTC
Read the original article Hit count: 178

Filed under:
|
|

I'm putting together PUT/DELETE links, a la Rails, which when clicked create a POST form with an hidden input labelled _method that sends the intended request type. I want to make it DRYer, but my jQuery knowledge isn't up to it.

HTML:

<a href="/articles/1" class="delete">Destroy Article 1</a>
<a href="/articles/1/publish" class="put">Publish Article 1</a>

jQuery:

$(document).ready(function() {

  $('.delete').click(function() {
    if(confirm('Are you sure?')) {
      var f = document.createElement('form');
      $(this).after($(f).attr({
        method: 'post',
        action: $(this).attr('href')
      }).append('<input type="hidden" name="_method" value="DELETE" />'));
      $(f).submit();
    }
    return false;
  });

  $('.put').click(function() {
    var f = document.createElement('form');
    $(this).after($(f).attr({
      method: 'post',
      action: $(this).attr('href')
    }).append('<input type="hidden" name="_method" value="PUT" />'));
    $(f).submit();
    return false;
  });

});

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery