Monday, May 28, 2018

html - jquery - Click event not working for dynamically created button




My requirement is to create number of buttons equal to the json array count. I was successful in creating buttons dynamically in jquery. But the method in .ready function of jquery is not called for the click action. I have tried searching in SO. Found few solutions but nothing worked for me. I am very new to jquery. Please help...



my code:
jQuery:




$(document).ready(function()
{
currentQuestionNo = 0;
var questionsArray;
$.getJSON('http://localhost/Sample/JsonCreation.php', function(data)
{
questionsArray = data;
variable = 1;
//CREATE QUESTION BUTTONS DYNAMICALLY ** NOT WORKING

for (var question in questionsArray)
{
var button = $("").attr("type", "button").attr("id", "questionButton").val(variable);

$('body').append(button);

//Tried using .next here - but it dint work...
//$('body').append('');
variable++;
}

displayQuestionJS(questionsArray[currentQuestionNo], document);
});




$("button").click(function()
{

if ($(this).attr('id') == "nextQuestion")

{
currentQuestionNo = ++currentQuestionNo;
}
else if ($(this).attr('id') == "previousQuestion")
{
currentQuestionNo = --currentQuestionNo;
}

displayQuestionJS(questionsArray[currentQuestionNo], document);


});



function displayQuestionJS(currentQuestion, document)
{
document.getElementById('questionNumber').innerText = currentQuestion.questionNumber;
document.getElementById('questionDescription').innerText = currentQuestion.quesDesc;
$('label[for=optionA]').html(currentQuestion.optionA);
$('label[for=optionB]').html(currentQuestion.optionB);

$('label[for=optionC]').html(currentQuestion.optionC);
}

HTML content


.  

















EDIT -- Sample .on Method code - Separate file: WORKING - THANKS A LOT













Answer



You create buttons dynamically because of that you need to call them with .live() method if you use jquery 1.7




but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:



$(document).on('click', 'selector', function(){ 
// Your Code
});


For Example




If your html is something like this




MyButton




You can write your jquery like this



$(document).on('click', '#btn-list .btn12', function(){ 

// Your Code
});

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...