Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating vertically grouped radio buttons with jQuery

I'm dynamically creating several vertically grouped radio buttons using jQuery mobile 1.0 for a multiple choice quiz.

When I paste this code from the JQM Radio Button Docs in it styles the controlgroup properly.

<fieldset data-role="controlgroup">
    <input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" />
    <label for="radio-choice-1">Cat</label>
    <input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2"  />
    <label for="radio-choice-2">Dog</label>
</fieldset>

When I dynamically inject my markup on pageshow() it injects the proper markup but it doesn't style the control group at all.

$.getJSON("assets/json/aircraft.json", function (data) {
    var maxQuestions = 10;
    var maxChoices = 4;

    var randomsorted = data.aircraft.sort(function (a, b) {
        return 0.5 - Math.random();
    });

    var quiz = $.grep(randomsorted, function (item, i) {
        return i < (maxQuestions * maxChoices);
    });

    var arr_quiz_markup = [];
    $.each(quiz, function (i, item) {
        var q = Math.floor(i / maxChoices);
        var c = i % maxChoices;

        if (c == 0) arr_quiz_markup.push("<div>Image for question " + q + " goes here...</div><fieldset data-role='controlgroup' data-question='" + q + "'>");

        arr_quiz_markup.push("<input type='radio' name='q" + q + "' id='q" + q + "c" + c + "' data-aircraftid='" + item.id + "' />");
        arr_quiz_markup.push("<label for='q" + q + "c" + c + "'>" + item.name + "</label>");

        if (c == maxChoices - 1 || c == quiz.length - 1) arr_quiz_markup.push("</fieldset><br />");

    });

    $("#questions").html(arr_quiz_markup.join("")).controlgroup("refresh");
});

I tried $("#questions :radio").checkboxradio("refresh"); but throws "cannot call methods on checkboxradio prior to initialization; attempted to call method 'refresh'".

My Live Quiz Demo (Sorry, jsfiddle doesn't have jQuery Mobile listed)

What am I doing wrong? How do I refresh this to properly get JQM to style the controlgroup correctly?

like image 869
Greg Avatar asked Jan 19 '12 07:01

Greg


1 Answers

Add this line

$("#quiz").trigger("create");

after

$("#questions").html(arr_quiz_markup.join("")).controlgroup("refresh");

This code snippet will force a rebuild of the quiz page so that jqm styles will be applied to the page contents.

like image 158
user700284 Avatar answered Oct 17 '22 21:10

user700284