Question

I've bound an event to an icon on click. The event changes the id of a button on the page. I want a new event to be bound to that new id, and the existing event bound to the old id to be unbound. How do I do this?

I can see from Firebug that the button id successfully changes when the icon is clicked. However, when I look at POST, I see that the hidden field with id "Final_Approval" has the value of "Approved", which tells me that the event tied to the original button id occurred, and I don't want it to. All of my jQuery is inside document ready.

The original button:

<button id="btn-final-approval-no-review" class="btn btn-warning" type="submit">Final Approval</button>

The original event tied to that id:

$('[id^="btn-final-approval"]').click(function () {
    $("#Final_Approval").val("Approved");
});

The event triggered when the icon is clicked:

$("#add-vendor-item").click(function () {
   $('#btn-final-approval-no-review').attr('id', 'btn-vendor-rep-review2');
}

The new event I want to take place:

$("#btn-vendor-rep-review2").click(function () {
    $("#ItemRequestStatusId").val("@Portal.BusinessModel.Entities.ItemRequestStatusId.VendorRepReview");
});
Était-ce utile?

La solution

To bind events to elements that change dynamically, you need to use delegation with on():

$(document).on('click', '[id^="btn-final-approval"]', function() {
    $("#Final_Approval").val("Approved");
});

As adeneo said, you probably shouldn't move IDs around, you should use classes. But the same idea applies, you just have to change the selector in the on() call.

Autres conseils

Use on delegate to bind click event dynamically.

$("body").on("click","#btn-vendor-rep-review2", function () {    
    $("#ItemRequestStatusId").val("@Portal.BusinessModel.Entities.ItemRequestStatusId.VendorRepReview");
});
$(document).on('click', '#finalApproval', function() {

if($(this).hasClass('first')){
    $(this).removeClass('first');
    //first action to be preformed    
}else{
  //second action to be preformed.
}


});

then simply add class first to the button on page load.

If you need it to toggle back you can just re-add the class first in the second action to be preformed area EDIT

after re-reading the question you probably cant use this - just substitute with the id / class of the item in question and add the if/else statement to the handler for that item.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top