0

Have a PREVIEW BUTTON. Clicking it initiates a function that generates new buttons with data attributes through ajax, appending to other html. Want to get the attribute value of "data-id" of the generated EDIT BUTTON, but the value comes up as "undefined".

var answer_id;
$(document).on('click', '#preview', function(){//PREVIEW button clicked
    ...some code...
    $.ajax({...});
    //ajax retrieves data and appends to html code
    //this data contains buttons.  One of the buttons is:
    //<button id="edit" type="button" class="btn" value="edit" data-id="521">Edit</button>
    answer_id = $('#edit').attr("data-id");
    alert(answer_id);
});

I can inspect the browser page code and the EDIT BUTTON has the data-id value as expected. However, the jquery alert that comes up says "undefined".

I have tried:

$('#edit').attr("data-id")
$("#edit").data("id")
$("#edit").data().value;

What is the error?

HDer
  • 385
  • 5
  • 17
  • Could you please share the bnt code? – Maksym Labutin Nov 24 '18 at 07:58
  • try to put `answer_id = $('#edit').attr("data-id");` inside `setTimeout();` and test if it work and you retrieve the value of `data-id` so the problem is that both `$.ajax` and `answer_id` working synchronously with other word `answer_id` grape the element `#edit` before it append to the html... is that work? – Amir Fawzy Nov 24 '18 at 08:03
  • No joke I made this post on Reddit. Answers your question https://www.reddit.com/r/programminghumor/comments/9sa0tr/you_have_to_wait_for_ajax/ – Cesar Bielich Nov 24 '18 at 08:04
  • changed ajax function to async: false, solved the problem. – HDer Nov 24 '18 at 09:21

0 Answers0