Samaan
Samaan

Reputation: 71

Target dynamically added button with jQuery (no event)

I would like to know a way to disable and enable, using jQuery, a dynamically added html button.

I'm aware of the .on() function, but in order to work, this function needs an event to listen to (like a click or something) and I don't have any event to bind because I'm calling it from a function.

This is the actual code, which is not working because the button with "#myID" is a partial which has been injected dynamically after the document ready():

 var validateForm = function(){
    if(exp_valid && cc_valid && ch_valid && cvn_valid){
        $('#myID').prop('disabled', false);
    }
 }

I would like a proper way to select, with no event, my dynamically added button.

Thank you for reading.

Upvotes: 0

Views: 109

Answers (3)

Lucas Lazaro
Lucas Lazaro

Reputation: 1526

What you can do is set a MutationObserver to watch for changes on your DOM elements, that way you can trigger a new check if something was added to your node tree.

Simplified JS:

var observer = new MutationObserver(function() {
  // This is where you run your function
  $('#myID').attr("disabled", true);
  console.log($('#myID'));
});

observer.observe(document.documentElement, {
    childList: true,
    subtree: true            
});

I've put together this demo, where a button is added dynamically and you can run your function again to check whether it should be disabled or not.

The full implementation is really well described in this article: http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/

Upvotes: 1

Samaan
Samaan

Reputation: 71

I managed to do it using :

  $('#myID').attr("disabled", true);

Thank you everyone for your time.

Upvotes: 0

ProEvilz
ProEvilz

Reputation: 5455

You can check if the button exists first

if ($(#myID).length) {
  $('#myID').prop('disabled', false);
}

Upvotes: 1

Related Questions