开发者问题收集

我如何从单选按钮获取价值

2020-11-10
60

在我的代码中,我想从单选按钮获取点击的值,当我单击一个或多个单选按钮时,它会获取该值并存储在数组中。知道如何使用 javascript 来实现吗

var myArray = ["Asian", "Thai", "Korean", "Chinese", "Mexican"];

var wrapper = document.getElementById('wrapper');

var elementsToInsert = [];

// Creation of the input with radio type and the labels
for(var i = 0; i < myArray.length; i++) {
  var radio = document.createElement('input');
  var label = document.createElement('label');
  radio.type = 'radio';
  radio.name = myArray[i];
  radio.value = myArray[i];

  label.setAttribute("for", myArray[i]);
  label.innerHTML = myArray[i];

  elementsToInsert.push({ label: label, radio: radio });
}

// Insert the labels and input in a random order
while(elementsToInsert.length !== 0) {
  var randomIndex = Math.floor(Math.random() * elementsToInsert.length);

  // Array.prototype.splice removes items from the Array and return the an array containing the removed items (See https://www.w3schools.com/jsref/jsref_splice.asp)
  var toInsert = elementsToInsert.splice(randomIndex, 1)[0];
wrapper.appendChild(toInsert.radio);
  wrapper.appendChild(toInsert.label);
  wrapper.appendChild(document.createElement('br'));
  
}
<div id="wrapper"></div>
1个回答

为您创建的输入元素添加一个 onclick 事件监听器函数,这将获取您点击的内容

示例

var myArray = ["Asian", "Thai", "Korean", "Chinese", "Mexican"];

var wrapper = document.getElementById('wrapper');

var elementsToInsert = [];

var output = [];

function handleClick(e) { // function defined
output.push(e.target.value)
console.log(output)
}

// Creation of the input with radio type and the labels
for(var i = 0; i < myArray.length; i++) {
  var radio = document.createElement('input');
  var label = document.createElement('label');
  radio.type = 'radio';
  radio.name = myArray[i];
  radio.value = myArray[i];
  radio.onclick = handleClick; // function added
  

  label.setAttribute("for", myArray[i]);
  label.innerHTML = myArray[i];

  elementsToInsert.push({ label: label, radio: radio });
}

// Insert the labels and input in a random order
while(elementsToInsert.length !== 0) {
  var randomIndex = Math.floor(Math.random() * elementsToInsert.length);

  // Array.prototype.splice removes items from the Array and return the an array containing the removed items (See https://www.w3schools.com/jsref/jsref_splice.asp)
  var toInsert = elementsToInsert.splice(randomIndex, 1)[0];
    wrapper.appendChild(toInsert.radio);
  wrapper.appendChild(toInsert.label);
  wrapper.appendChild(document.createElement('br'));
  
}
Biswa Soren
2020-11-10