0

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.

3
  • 1
    This is easy, you just have to wait for the button to be there, you can't change something that doesn't exist. Commented Oct 14, 2016 at 15:37
  • Selecting dynamically added elements is no different from selecting any other element. If it exists in the document, you can select it. If you have an issue, provide an actual reproduction of that issue. Commented Oct 14, 2016 at 15:38
  • I can target my button and this works $('#myID').show(); But im not able to enable nor disable my button, the prop('disabled', true) should work... Commented Oct 14, 2016 at 15:58

3 Answers 3

1

You can check if the button exists first

if ($(#myID).length) {
  $('#myID').prop('disabled', false);
}
Sign up to request clarification or add additional context in comments.

1 Comment

$('#myID).length is returning 1, but I still can't disable or enable my button.
1

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/

1 Comment

Thank you for sharing this approach and ressources. This is wonderful !
0

I managed to do it using :

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

Thank you everyone for your time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.