Hadi
Hadi

Reputation: 17299

Action not working when button is added with ajax

I've added button in html by ajax and it has onclick event.

if(response.status == "SUCCESS"){
    steps = "";
    for(i = 0 ; i < response.result.length ; i++){
      steps +="<br>
      <div >
        <input type='button' value='ok'   id='button'   onclick='action()' class='button'>
      </div>";
     }
     $('#info').html(steps);
}

when i'm clicking on button, action of button not raise.why?

Upvotes: 0

Views: 61

Answers (2)

PeterKA
PeterKA

Reputation: 24638

Please change your code to this -- try not to duplicate IDs, they should be unique and avoid inline JS:

if(response.status == "SUCCESS") {
    steps = "";
    for(i = 0 ; i < response.result.length ; i++){
        steps +="<br><div ><input type='button' value='ok' class='button'></div>";
    }
    $('#info').html(steps);
}

And then use this separately and not within any loop.

$(function() {
    $('#info').on('click', 'input.button', action);
});

Upvotes: 1

Jasper
Jasper

Reputation: 76003

Try:

$('#info').html(steps).find('.button').on("click", action);

and remove the onclick attribute from the button's HTML.

It seems likely that since you are adding these elements after the page load that their onclick attributes are not adding event handlers to the elements.

Also, you've got a loop giving each element the same ID but IDs are supposed to be unique.

Upvotes: 1

Related Questions