I have the following HTML:
<div id="dynamicRadioButtons">
</div>
Using jQuery I’d like to append a radio button with corresponding label to the above div. An example of the HTML I’d like to append is as follows:
<input type="radio" id="dynamicRadio" name="radio" /><label for="dynamicRadio">My Label</label> <br>
So, lets say I have a function that’s called when I click something and takes the parameters id (which is the id of the radio button to be created) and labelText (which is the text of the label to be created), I want to be able to do something like this:
function OnClick(id, labelText){
// create a new radio button using supplied parameters
var $newRadioBtn = $('<input />').attr({type="radio", id=id, name="radio"});
// create a new radio button using supplied parameters
// TODO - set the value of the label to parameter: labelText
var $newLabel = $('<label />').attr({for=id});
// TODO - append the new radio button and label to the div and then append <br>...
$('#dynamicRadioButtons').append(/* The elements I want to append */);
}
Can someone help me with my TODO bits please? I was following an example as per this page but just don’t know enough about jQuery to add the label etc. Also is this the best way to dynamically add HTML elements?
You can wrap your label around the form element, which means you don’t have to be quite so verbose.
And you can create it like this:
I have used the supplied id for the name and id, otherwise all radios would have a name of “radio”. You might also want to rename
OnClickas there are build in event handlers calledonclickand it might cause confusion.Here is an example JS Fiddle