How can I get value from radio button
In my code I want to get the clicked value from radio button when I click one or more radio button it get the value and store in array. any idea how can I do it using 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>
Answer
Add a function on onclick
event listener to the input element that you have created, this will get you what you have clicked
Example
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')); }