I am not familiar with javascript. can anyone tell me how to print the selected value in javascript for below code please?
<form>
What color do you prefer?
<input type="radio" name="colors" id="red">Red
<input type="radio" name="colors" id="blue">Blue
</form>
CodePudding user response:
Well you can console.log
it or add it inside another element on page. The following is an example.
document.querySelectorAll("input").forEach(function(elem) {
elem.addEventListener("input", function(ev) {
var value = elem.closest("label").innerText
console.log(value)
// or
document.getElementById("output").innerText = value
})
})
<form>
What color do you prefer?
<label><input type="radio" name="colors" id="red">Red</label>
<label><input type="radio" name="colors" id="blue">Blue</label>
</form>
<p id="output"></p>
CodePudding user response:
First give your inputs the "value" attribute , then just select element and use "value" property to access , also check if it is checked or not.
Ex:
<input type="radio" value="red"
name="colors" id="red"/>
then:
let red=document.querySelector("#red");
if(red.checked){
console.log(red.value);
}