Why won't my dynamically created buttons disable on click?

I have a page that dynamically creates multiple buttons with IDs like id='rbutton_" + i + "'. Below is my HTML code:

< button type=‘button’ id=‘rbutton_" + i + "’ onclick=‘disable(" + i + ");’ > Click me </button >

And here is my JavaScript function:

function disable(i){ $(“#rbutton_” + i).attr(“disabled”, “disabled”); }

However, the button does not get disabled when I click on it. How can I fix this?

Hey Keerti,

Correct String Concatenation in jQuery Selector

< button type=‘button’ id=‘rbutton_" + i + “’ onclick=‘disable(” + i + ");’ > Click me

Ensure that the string concatenation in the jQuery selector is correct. The issue might be using single and double quotes within the id attribute.

The below script must be written within the script tag:

> function disable(i){
>     $("#rbutton_" + i).attr("disabled", "disabled");
> }

Explanation: Ensure the id is constructed correctly within the jQuery selector. Use " around the button ID and ’ for string concatenation.

Hey Madhurima,

Use this to Refer to the Button:

Modify the HTML and JavaScript to pass the button element directly to the disable function using this.

< button type=‘button’ id=‘rbutton_" + i + “’ onclick=‘disable(this);’ > Click me

function disable(i){

$(“button”).attr(“disabled”, “disabled”);

}

Explanation: Pass the button element directly using this in the onclick attribute. The disable function receives the button element and disables it directly.

Hey keerti

I suggest you to use the Vanilla JavaScript to Disable the Button

 function disable(i) {
 
 document.getElementById('rbutton_' + i).disabled = true;

  }

Explanation:

Use document.getElementById to select the button by its ID. Set the disabled property to true to disable the button. This approach does not require jQuery and works with pure JavaScript.