-3

my problem

What I need to do is: I have a simple input field, and below that I have a dropdown list with options: Checkbox and Radio. The user needs to write something in the input field and select the type. For example:

Input field: One, Two, Three  
Radio  

and the outcome will be 3 radio buttons with titles One Two Three. The problem here is that I don't know how to separate the inputs (they have to be separated by a comma). So far, I managed to get this, but as you can see, I'm not getting what I need to get.

I tried to find solution but I'm kinda new so I don't know how to do it. Btw, it needs to be done in Javascript and HTML only. Here is my code

function create() {
  var items = document.getElementById("items")
  items = items.value
  var type = document.getElementById("type")
  type = type.value
  var result = document.getElementById("result")
  result.innerHTML += "<input type='" + type + "'>" + items
}
<h2>Form</h2>
<div>
  <span>Items: </span><input type="text" id="items">
</div>
<div>
  <span>Type: </span>
  <select id="type">
    <option>Checkbox</option>
    <option>Radio</option>
  </select>
</div>

<button onclick="create()">Create</button>
<div id="result"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Anon748
  • 7
  • 2

1 Answers1

-1

You want to use split

I use Array.map and template literals to generate the HTML

I have used recommended eventListeners and also made the radios/checkboxes work since radios need the same name and the checkbox not

window.addEventListener("DOMContentLoaded", () => { // when page has loaded
  const nameField = document.getElementById("names");
  const typeField = document.getElementById("type");
  const createBut = document.getElementById("create");
  const resultDiv = document.getElementById("result");
  createBut.addEventListener("click", () => {
    const names = nameField.value.trim().split(/,\s?/); // split on comma with or without trailing space
    console.log(names);
    const type = typeField.value;
    resultDiv.innerHTML = names
      .map(name => `<label><input type="${type}" 
      name="${type==='checkbox' ? name : 'rad'}" 
            ${type==='checkbox' ? '' : `value="${name}"`}"/>${name}`).join('<br/>');
  });
});
Items: <input id="names" /><br /> Type:
<select id="type">
  <option value="radio">Radio</option>
  <option value="checkbox">Checkbox</option>
</select><br />
<button type="button" id="create">Create</button>
<div id="result"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236