My goal is to extract the id
and value
from a selected radio button. After coming across similar code in various posts and blogs, I decided to implement it in Angular 2.
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
I found this snippet here: Get Radio Button Value with Javascript
In my Angular class, I attempted to implement it like so:
selected = {value1: '', value2: ''}; //where I want the results to be stored.
//custom function with the snippet implemented
getSelected() {
const radios = document.getElementsByName(this.quesForm.value.name);
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].click){
this.selected.value1 = radios[i].getAttribute("id");
this.selected.value2 = radios[i].getAttribute("value");
break;
}
}
}
//calling it here in an attempt to make sure it detects when the selection changes.
ngOnChanges() {
this.getSelected();
console.log(this.selected);
}
This is how my template is structured:
<div *ngFor="let ans of quesForm.value.answers">
<input type="radio"
[attr.name] = "quesForm.value.name"
[attr.id] = "ans.id"
[attr.value] = "ans.answer"
/>
<label>{{ans.answer}}</label>
</div>
Despite not encountering any errors, I'm not seeing any results being logged. Additionally, I have an empty space set up outside of the form
tag to display the results which remains blank.
<p>{{selected | json}}</p>
What might be causing this issue?