jQuery dynamically generated radio buttons then value is passed to continue button
I have a page that receives a JSON response. If there is more than one option in the JSON it will dynamically generate some radio buttons using a for loop in Javascript based on the greater length.
Something like:
for (var i = 0; i < length; i ++){
alert(开发者_StackOverflowi);
//draw the HTML radio buttons based on the data i++
}
//value from radio button button gets passed to a continue button
What would be the best way to do that in jQuery?
Something like
for ( var i in json ) {
var input = $('<input>', {
type: 'radio', name: 'group-name',
value: json[i],
'class': 'my_radio'
} );
$('body').append( input );
}
$('#continue').click( function() {
var selected = null;
$('input.my_radio').each( function() {
if ( $(this).attr( 'selected' ) )
selected = $(this).val();
});
// do something with selected....
});
You'll have to surround it with a form element if you need that. I haven't tested this, by the way.
精彩评论