Home > Blockchain >  Get checked value from radio button group
Get checked value from radio button group

Time:02-10

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.

CodePudding user response:

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.

CodePudding user response:

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);
  • Related