Splice function in javascript not working properly

Viewed 117

The button on click should generate radio buttons, one at a time, but I have an issue with the text node that should stick with the radio buttons. Here's part of the code:

var array = [];
items = document.getElementById("items").value.split(",");
for (var i = 0; i < items.length; i++) {
    array.push(items[i]);
}
type = document.getElementById("type");
container = document.getElementById("container");
if (type.value == "radio") {
    radio = document.createElement("input");
    radio.setAttribute("type", "radio");
    for (var i = 0; i < array.length; i++) {
        text = document.createTextNode(array[0]);
        container.appendChild(text);
        container.appendChild(radio);
        array.splice(0,1);
    }
}

form screenshot

So this is the result, but I want the first radio button to have a value of '1', the second '2' etc.

1 Answers

First you don't need array the items array already contains the elements you want from text input

Also no need to slice/splice any array

Your problem was that you have to create another unique radio element for every element so what you did is appending same radio element many times which result in adding the radio button once

so you have to put radio = document.createElement("input"); radio.setAttribute("type", "radio"); inside the for loop . . . .

function Z() {
  items = document.getElementById('items').value.split(",");
  type = document.getElementById("type");
  container = document.getElementById("container");
  container.innerHTML = "";
  if (type.value == "radio") {
    for (var i = 0; i < items.length; i++) {
      text = document.createTextNode(items[i]);
      radio = document.createElement("input");
      radio.setAttribute("type", "radio");
      container.appendChild(text);
      container.appendChild(radio);
    }
  }
}
<input onkeyup="Z()" id="items"> type:
<select id="type">
  <option value="radio">Radio</option>
  <option value="checkbox">Text</option>
</select>

<div id='container'></div>

Related