'Get checked value from radio button group
I am populating radio buttons dynamically, and on submit button click I need to get value of the checked radio button from the group.
<ul data-bind="foreach: Numbers">
<li>
<input name="phone-group" type="radio" data-bind="attr: {'id': $data.id}, value: $data.value" >
<label data-bind="Text: $data.value, attr:{'for': $data.id }" ></label>
</li>
</ul>
<button role="link">Submit</button>
This is the model: (coffeescript)
@Numbers = ko.observableArray([{id:"1",value:"1234"}, {id:"2",value:"5678"}, {id:"3",value:"91011"}])
On submit button click, I need the selected value from the radio button list.
Solution 1:[1]
Consider using:
function getRBtn(rbName) {
let opt = document.querySelector(`input[name=${rbName}]:checked`);
return opt = (opt != null) ? opt.value : 'memo0'; // default value 'memo0'
}
// rbName is the radio button name value
// opt.value is the value associated with the radio button
// 'memo0' is a default value if no radio buttons have been selected.
Solution 2:[2]
I don't know how to get the checked value in CoffeeScript. However, in JavaScript, using the name attribute on the input, you can get the checked value using document.querySelector() method:
let checkedValue = document.querySelector('input[name="phone-group"]:checked').value;
console.log(checkedValue);
Solution 3:[3]
To do this in a knockoutjs way, the only thing I can see missing is you are not using the checked binding to get the value selected.
var ViewModel = function() {
var self = this;
self.Numbers = ko.observableArray([{
id: "1",
value: "1234"
}, {
id: "2",
value: "5678"
}, {
id: "3",
value: "91011"
}]);
self.selectedNumber = ko.observable();
self.submit = function(){
alert("selected Number: " + self.selectedNumber());
}
}
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: Numbers">
<li>
<input name="phone-group" type="radio" data-bind="attr: {'id': $data.id}, value: $data.value, checked: $parent.selectedNumber">
<label data-bind="text: $data.value, attr:{'for': $data.id }"></label>
</li>
</ul>
<button role="link" data-bind="click: submit">Submit</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jmrker |
| Solution 2 | Utku Demir |
| Solution 3 | Nathan Fisher |
