I have a drop down select and I want to change it to radio button:
HTML
<select id="designation" title="Designation" name="designation">
<option value="">Choose Option..</option>
<option value="1">Educator</option>
<option value="2">Student Subscriber</option>
<option value="3">Adult Subscriber</option>
</select>
<div id="r"></div>
I try to add this code but is display only the buttons without labels, how I can add labels too?
Jquery
jQuery("#designation option").each(function(i, e) {
jQuery("<input type='radio' name='r' />")
.attr("value", jQuery(this).val())
.attr("checked", i == 0)
.click(function () {
jQuery("#designation").val(jQuery(this).val());
})
.appendTo("#r");
});
I have a drop down select and I want to change it to radio button:
HTML
<select id="designation" title="Designation" name="designation">
<option value="">Choose Option..</option>
<option value="1">Educator</option>
<option value="2">Student Subscriber</option>
<option value="3">Adult Subscriber</option>
</select>
<div id="r"></div>
I try to add this code but is display only the buttons without labels, how I can add labels too?
Jquery
jQuery("#designation option").each(function(i, e) {
jQuery("<input type='radio' name='r' />")
.attr("value", jQuery(this).val())
.attr("checked", i == 0)
.click(function () {
jQuery("#designation").val(jQuery(this).val());
})
.appendTo("#r");
});
Share
Improve this question
edited Jul 25, 2016 at 16:39
I'm Geeker
4,6375 gold badges24 silver badges42 bronze badges
asked Jul 25, 2016 at 16:28
RobertRobert
8123 gold badges19 silver badges49 bronze badges
1
-
radio labels are extra html. you never provide that extra html. e.g.
<input type="radio" name="foo" value="bar"> Bar
- putting inBar
is up to you. – Marc B Commented Jul 25, 2016 at 16:33
3 Answers
Reset to default 3You have to create it separately,
jQuery("#designation option").each(function(i, e) {
(jQuery("<input type='radio' name='r' />")
.attr("value", jQuery(this).val())
.attr("checked", i == 0)
.click(function() {
jQuery("#designation").val(jQuery(this).val());
}).add($("<label>"+ this.textContent +"</label>")))
.appendTo("#r");
});
DEMO
Check out this DEMO
$('#designation option').each(function() {
var label = $(this).html();
var value = $(this).attr('value');
if(value != ""){ // Here it will remove empty values
$('#r').append('<td><input type="radio" name="r" value="'+value+'">'+label+'</td>');
}
});
Add label and remove the choose option radio
Also use .remove()
to remove the dropdown after creating radio input.
jQuery("#designation option").each(function(i, e) {
if(i != 0) {
(jQuery("<input type='radio' name='r' />")
.attr("value", jQuery(this).val())
.attr("checked", i == 1)
.click(function() {
jQuery("#designation").val(jQuery(this).val());
}).add($("<label>"+ this.textContent +"</label>")))
.appendTo("#r");
}
});
jQuery("#designation").remove();
DEMO