user2596635
user2596635

Reputation: 381

Any way to change a list of radio buttons to a select drop down dynamically?

I'm trying to find a work around to a dynamically created form that for whatever reason doesn't give the option of a select list, only radio and check inputs. There is no way for me to go in and change the code so I was curious if there is a way to transform a list of radio buttons to a select drop down using jquery?

for example, if I have this code:

<form>
   <div class="col-lg-5">     
      <p class="bullet"><b><font class="required" size="3" color="FF0000">*     </font></b></p>
      <p class="inputLabel">First Name:</p>
      <input type="text" size="25" name="Text1" value="">
   </div>
   <div class="col-lg-5">
      <input type="radio" name="gender" value="male">Male<br>
      <input type="radio" name="gender" value="female">Female
   </div>
   <div class="col-lg-10"><p>Current Employer / Facility:</p>
      <input type="text" size="25" name="Text9" value="">
   </div>
</form>

is there anyway to change it to:

<form>
    <div class="col-lg-5">     
      <p class="bullet"><b><font class="required" size="3" color="FF0000">*     </font></b></p>
      <p class="inputLabel">First Name:</p>
      <input type="text" size="25" name="Text1" value="">
   </div>
    <select name="gender">
       <option value ="male">Male</option>
       <option value ="female">Female</option>
    </select>
   <div class="col-lg-10"><p>Current Employer / Facility:</p>
      <input type="text" size="25" name="Text9" value="">
   </div>
</form>

Upvotes: 0

Views: 926

Answers (3)

j08691
j08691

Reputation: 207923

Here's one way:

var sel = $('<select name="gender">').append(function () {
    var opts='';
    $('input[name="gender"]').each(function () {
        opts += '<option value ="' + this.value + '">' + this.value.charAt(0).toUpperCase() + this.value.slice(1) + '</option>';
    })
    return opts;
});
$('form div.col-lg-5:eq(1)').empty().append(sel);

jsFiddle example

Upvotes: 1

Frank
Frank

Reputation: 664

This JSFiddle is as close as I was able to get it.

HTML:

<form>
   <input type="radio" name="gender" value="male">Male<br>
   <input type="radio" name="gender" value="female">Female
</form>

Javascript:

var select = $('form').append($('<select>', {
    name: 'gender',
    id: 'genderSelect'
}));

$("form > input[type='radio']").each(function() {
    $('#genderSelect').append($('<option>', {
        value: $(this).val(),
        text: $(this).val()
    }));
    $(this).remove();
});

You'll need to do something with the labels for the radio buttons to grab the values or get rid of them more easily.

Upvotes: 0

Sherif Ahmed
Sherif Ahmed

Reputation: 1946

var select = $("<select></select>").attr("name", "gender");
$('form input[name="gender"]').each(function(index, item) {
    $('<option/>', {
         'value': this.value,
         'text': this.value
    }).appendTo(select);
});

Upvotes: 0

Related Questions