JQuery Convert Select for radio buttons?

I am trying to convert select rectangles to radio buttons on the fly using jquery, and I'm not sure what the best way is.

HTML example:

<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 when loading a page 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 should be dynamic, so it will cycle dynamically for each selection window and each parameter inside (since different products have different parameters)

I am trying to understand the best way. Either get a multidimensional array of all values ​​first, and then create radio buttons .. or swap them one at a time in the loop. Currently an attempt by the first, but I think I can overdo 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 had some secret / easier way to do this that I am missing?

+7
jquery select radio-button dropbox
source share
2 answers

I put this together and tested it in several browsers, everyone seems to be doing it well. It will output the data from the <option> elements and create <input/><label/><br/> for each of them, and then delete the selection 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(); }); 
+23
source share

You are on the right track. Iterate and collect the selected data into variables and do as little DOM work operations as possible (to increase efficiency) to create radio inputs.

+1
source share

All Articles