Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This is a dynamically generated page with multiple forms where each form contains a button which is
- // either an add or delete button and toggles on click. The form actions gracefully degrade. The original
- // button always works with ajax, but the second doesn't rebind. I tried using the event delegation pattern
- // and the copy events to no avail. The fact that the whole form needs to get replaced seems to be the problem
- // since this isn't a simple append.
- //
- // Here is the HTML that we start with (for example):
- //<td id="td_14"> <form class="create" method="post" action="/cart_items" id="14"> <input type="hidden" name="id" value="14" />
- //<input type="hidden" name="to" value="/tags" />
- //<button type="submit" id="14" class="button positive"><img src="/stylesheets/lib/img/icons/tick.png" alt="" />Add</button>
- //</form>
- //</td>
- // or
- //
- //<td id="td_3"> <form class="delete" method="post" action="/cart_items/3" id="3"> <input type="hidden" name="to" value="/tags" />
- //<input type="hidden" name="_method" value="delete" />
- //<button type="submit" id="3" class="button remove"><img src="/stylesheets/lib/img/icons/tick.png" alt=""/>Remove</button>
- //</form>
- //</td>
- // Here is the javascript using jquery
- $(document).ready(function(){
- $('.delete').click(function(event){
- var id = $(this).attr("id")
- var $newForm = $('<form method="post" action="/cart_items" id="' + id + '" class="create"><input type="hidden" name="id" value="' + id + '" /><button id="' + id + '" type="submit" class="button positive"><img src="/stylesheets/lib/img/icons/tick.png" alt=""/> Add</button></form>');
- var $tgt = $(event.target);
- if ($tgt.is('button')) {
- $.ajax({
- type: "POST",
- data: {_method: "delete"},
- url: '/cart_items/' + id,
- dataType: "script",
- beforeSend: function(xhr){ confirm("Are you sure?");},
- success: function(data, status) {
- $tgt.parent().replaceWith($newForm);
- }
- });return false;
- }
- });
- $(".create").click(function(event){
- var id = $(this).attr("id")
- var $newForm = $('<form method="post" action="/cart_items/' + id + '" id="' + id + '" class="delete"><input type="hidden" name="_method" value="delete" /><button type="submit" id="' + id + '" class="button remove"><img src="/stylesheets/lib/img/icons/tick.png" alt=""/> Remove</button></form>');
- var $tgt = $(event.target);
- if ($tgt.is('button')) {
- $.ajax({
- type: "POST",
- data: {id: id},
- url: "/cart_items",
- dataType: "script",
- success: function(data, status) {
- $tgt.parent().replaceWith($newForm);
- }
- });return false;
- }
- });
- });
Add Comment
Please, Sign In to add comment