kandarp
kandarp

Reputation: 1101

Replace radio buttons with select element using Javascript

I need dynamic script which detects radio button by name and replace it with select element.

These radio buttons can be anywhere in the DOM. I need to distinguish using names and replace it with relevant select-box.

For example input :

<tr>
    <td>
        Car Type
    </td>
    <td>
        <input type="radio" name="Type"> Old
        <input type="radio" name="Type"> New
    </td>
</tr>

Required output :

<tr>
    <td>
        Car Type
    </td>
    <td>
        <select name="Type">
            <option value="Old">Old</option>
            <option value="New">New</option>
        </select>
    </td>
</tr>

I tried something, but no success (My Script)

//removing all radio
  var radios = document.getElementsByName(name);
  for (var i = 0; i < radios.length; i++) {
    radios[i].parentNode.removeChild(radios[i]);
  }
  //replaceing wih select
  var selectList = document.createElement("select");
  selectList.name = name;
  radios[0].parentNode.appendChild(selectList);
  //Create and append the options
  for (var i = 0; i < data.length; i++) {
    var option = document.createElement("option");
    option.value = data[i];
    option.text = data[i];
    selectList.appendChild(option);
  }

Plunker full example

Upvotes: 3

Views: 894

Answers (1)

Serge K.
Serge K.

Reputation: 5323

I changed a bit your code to make it clearer and functionnal.

  1. I changed document.getElementsByName to document.querySelectorAll in order to have a static NodeList, otherwise you would have to use a while since the collection will reflect changes made when a radio button is removed. You could also remove them later but it would be multiplying for-loops for no reason. Moreover querySelectorAll('input[type="radio"]... focus only on radio buttons, avoiding errors.
  2. I got the label text using .nextSibling to affect it to the option and used trim to remove useless white space and line breaks.
  3. I used remove to remove the radios and labels from the DOM.
  4. As a side note, radio buttons are meant to have a value. You shouldn't rely on the label IMO.

function replaceRadiosBySelect(name) {
  var selectList = document.createElement('select'),
      radios     = document.querySelectorAll('input[type="radio"][name="' + name + '"]');
  
  if (radios.length > 0) {
    selectList.name = name;
    radios[0].parentNode.appendChild(selectList);

    for (var i = 0; i < radios.length; i++) {
      var label  = radios[i].nextSibling,
          option = document.createElement('option');

      option.value = option.text = label.data.trim();
      selectList.appendChild(option);

      radios[i].remove();
      label.remove();
    }
  }
}

replaceRadiosBySelect('Type');
<tr>
  <td>
    Car Type
  </td>
  <td>
    <input type="radio" name="Type"> Old
    <input type="radio" name="Type"> New
  </td>
</tr>

Upvotes: 1

Related Questions