I am trying to convert select boxes to radio buttons on the fly using jquery, and I'm not sure the best way.
Example HTML:
<form id="product">
<select name="data[123]">
<option value="1">First</option>
<option value="2">Second</option>
......
<option value="n">xxxxxx</option>
</select>
</form>
I want to convert it at page load using jquery to:
<form id="product">
<input type="radio" name="data[123]" value="1" />
<label for="data[123]">First</label><br/>
<input type="radio" name="data[123]" value="2" />
<label for="data[123]">Second</label><br/>
......
<input type="radio" name="data[123]" value="n" />
<label for="data[123]">xxxxxx</label><br/>
</form>
And it needs to be dynamic so it will loop dynamically for each select box and each option inside (as different products have different options)
I'm trying to figure the best way. Either to get a multidimensional array of all the values first and then build the radio buttons.. or swap them out one at a time in a loop. Currently attempting the former, but I think I may be overthinking it:
$(document).ready(function(){
//Get Exising Select Options
$('form#product select').each(function(i, select){
$(select[i]).find('option').each(function(j, option){
//alert($(option).text());
option[j] = [];
option[j]['text'] = $(option).text();
option[j]['val'] = $(option).val();
});
});
//Remove Select box
$('form#product select').remove();
});
Has anyone tried this or have some secret/easier way of doing it that I'm missing?
I put this together, and tested it in a few browsers, all seem to handle it well. It will take the data out of the <option>
elements and create the <input/><label/><br/>
for each one, then remove the select box.
//Get Exising Select Options
$('form#product select').each(function(i, select){
var $select = $(select);
$select.find('option').each(function(j, option){
var $option = $(option);
// Create a radio:
var $radio = $('<input type="radio" />');
// Set name and value:
$radio.attr('name', $select.attr('name')).attr('value', $option.val());
// Set checked if the option was selected
if ($option.attr('selected')) $radio.attr('checked', 'checked');
// Insert radio before select box:
$select.before($radio);
// Insert a label:
$select.before(
$("<label />").attr('for', $select.attr('name')).text($option.text())
);
// Insert a <br />:
$select.before("<br/>");
});
$select.remove();
});
You're on the right track. Iterate and collect the select data into variables and make as few DOM operation calls as possible (for efficiency) to create the radio inputs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With