80

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 = $("<input>").attr("type", "button").attr("id", "questionButton").val(variable);

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

                        //Tried using .next here - but it dint work...
            //$('body').append('<button id="questionButton">' + variable + '</button>');
            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
<form method="post" name="formRadio">

<label id="questionNumber"></label>. &nbsp;
<label id="questionDescription"></label>   <br />
<input type="radio" id="optionA"> </input> <label for="optionA"></label> <br />
<input type="radio" id="optionB"> </input> <label for="optionB"></label> <br />
<input type="radio" id="optionC"> </input> <label for="optionC"></label> <br />

<button id="previousQuestion">Previous Question</button>
<button id="nextQuestion">Next Question</button>

<br />
<br />

<input type="submit" id="submitButton" name="submitTest" value="Submit"></input>
</form>

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

<script>
$(document).ready(function()
{
    $("button").click(function()
    {
        var button = '<input type="button" id="button2" value="dynamic button">';
        $('body').append(button);
    });
});

$(document).on('click','#button2', function()
{
    alert("Dynamic button action");
});

</script>
</head>

<body>

<button id="button">Static Button</button>

</body>
vivin
  • 992
  • 1
  • 8
  • 24
  • @Barmer Can anyone please let me know why is the below code not working? $(document).on('click', 'button', function(e) { alert("asd"); }); – vivin Dec 29 '13 at 09:21

4 Answers4

179

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

<div id="btn-list">
    <div class="btn12">MyButton</div>
</div>

You can write your jquery like this

$(document).on('click', '#btn-list .btn12', function(){ 
     // Your Code
});
Majid Golshadi
  • 2,686
  • 2
  • 20
  • 29
  • 5
    This method is fantastic. It uses the document object and finds whatever buttons are there, whether old or new (dynamically created). – Josh Beam Dec 28 '13 at 21:40
  • @majid, even $(document).on('click', 'button', function(){ alert("asd"); }); is not working.... On tap of a dynamically created button, alert is not popping up... Any help would be greatly appreciated... – vivin Dec 29 '13 at 09:09
  • @vivin, i add an Example to my Answer – Majid Golshadi Dec 29 '13 at 09:21
  • @majid... Done Sir. One more clarification. Inside my getjson function, I have questionsArray. When i try to access question.questionNumber, i get a "undefined" message. My json looks like [{"questionNumber":"1","quesDesc":"The price...?","optionA":"25%",...,"selectedAnswer":null},{"questionNumber":"2","que‌​sDesc":"Price ...?","optionA":"9.09%",...,"selectedAnswer":null},...]. No issues in the Format. Please let me know how to access the values in the json data using the same for loop... – vivin Dec 29 '13 at 17:35
  • i can't answer your question in comment clearly but this link answer your question http://stackoverflow.com/questions/2342371/jquery-loop-on-json-data-using-each – Majid Golshadi Dec 29 '13 at 18:54
  • I didn't know about this new technique $(document).on('click', '#ID', function(){ } I was trying with the old $("button").click(function(){} technique and wasted my most of the day. Thanks alot man! – sohaiby May 23 '14 at 12:24
  • Its working , is ther any way to bind the button to an event ynamically , to call a function – Anoop P S Oct 23 '19 at 12:24
7

My guess is that the buttons you created are not yet on the page by the time you bind the button. Either bind each button in the $.getJSON function, or use a dynamic binding method like:

$('body').on('click', 'button', function() {
    ...
});

Note you probably don't want to do this on the 'body' tag, but instead wrap the buttons in another div or something and call on on it.

jQuery On Method

jrpotter
  • 161
  • 1
3

the simple and easy way to do that is use on event:

$('body').on('click','#element',function(){
    //somthing
});

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

Aashish
  • 31
  • 3
-1

You could also create the input button in this way:

var button = '<input type="button" id="questionButton" value='+variable+'> <br />';


It might be the syntax of the Button creation that is off somehow.

Bam
  • 478
  • 6
  • 19