Reputation: 550
When I dynamically insert radio buttons from inside an API call function, the resulting buttons don't get marked as "checked" when you click on them, meaning they don't work correctly. They get the "ui-radio-on" class, but not the checked attribute, which means the .change() event doesn't fire either. Why?
// Show places list
user.getConnections("worksat", function(error, data, connections){
for(var i = 0; i < connections.length; i++) {
var connection = connections[i];
var place = connection.name;
// Add place where person works at to list
$('#radio-clock-in').append('<label><input type="radio" name="clock-place" id="clock-' + place + '" value="' + place + '" />' + place + '</label>');
}
// refresh radio buttons
$('input[type=radio]').checkboxradio();
});
//If I put the same .append() code right here, the button will behave normally
Also, the buttons style correctly, but don't acknowledge that they're inside a control group, so they're spread out instead of neatly packed.
<div data-role="panel" id="places">
<fieldset data-role="controlgroup" id="radio-clock-in">
<!-- Dynamically injected radio buttons go here -->
</fieldset>
</div>
jquery mobile v1.4.0-rc1
*Update: Just wanted to note that if I put the exact same code outside of the user.getConnections function, the buttons work (attr gets checked) and the .change() event fires. I'm thinking it's something to do with the lag of the api call interfering.
Upvotes: 1
Views: 205
Reputation: 31732
To attach event to radio buttons which are dynamically created:
$("static_parent").on("change", "dynamic_element", function () {
// code
});
You can place it outside user.getConnections function.
To have checkbox / radio work correctly, you need to give each one a unique id, and add for=id
to label tag.
<label for="unique_id"><input type="radio" name="clock-place" id="unique_id" value="" />Place</label>
Another note, elements should be appended to .controlgroup("container")
.
$('#radio-clock-in').controlgroup("container").append(elements);
And then, refresh controlgroup.
$('#radio-clock-in').controlgroup("refresh");
Upvotes: 2
Reputation: 550
Turns out I just needed to move my event listener inside of the user.getConnections function:
$('[name=clock-place]').change(clockIn);
The control group not "grouping" is still pretty weird, although it works correctly if I create the radio list before this particular page shows.
Upvotes: 0