Search code examples
c#javascripthtmlasp.netfor-attribute

Get value from html label assiociated with radiobutton using FOR attribute


A html form with radio buttons which is assiociated with HTML label which looks like this.

<form action="demo_form.aspx">
  <label for="male">Male</label>
  <input type="radio" name="sex" id="male" value="male"><br>
  <label for="female">Female</label>
  <input type="radio" name="sex" id="female" value="female"><br>
  <input type="submit" value="Submit">
</form> 

how to get values when user clicks radio buttons either using java script or using server-side script (ASP.Net- C#) ? And also which one of this will be more appropriate to use.


Solution

  • Try this Script:

        window.onload = function () {
        var btnSubmit = document.getElementById('btn-submit');
        btnSubmit.onclick = function (e) {
            e.preventDefault();
            var radioInputs = document.querySelectorAll('#myform input[type="radio"][name="sex"]');                 
            for (var i = 0; i < radioInputs.length; i++) {
                if (radioInputs[i].checked)
                {
                    var value = getlabelforValue(radioInputs[i]);
                    alert(value);
                }
            }
            document.getElementById("myform").submit();
        };
    };
    
    function getlabelforValue(inputname) {
        var labelElements = document.querySelectorAll('#myform label');
        for (var i = 0; labelElements[i]; i++) {
            console.log(labelElements[i]);
            if (labelElements[i].getAttribute('for') == inputname.getAttribute('id')) {
                return labelElements[i].innerText || labelElements[i].textContent;
            }
        }
        return null;
    }
    

    Html:

    <form id="myform" action="demo_form.aspx">
        <label for="male">Male</label>
        <input type="radio" name="sex" id="male" value="male" /><br />
        <label for="female">Female</label>
        <input type="radio" name="sex" id="female" value="female" /><br />
        <input type="submit" id="btn-submit" value="Submit">
    </form>
    

    Here is the Demo

    Or

    In code behind you can do this to get value.

    string radioValue = String.Format("{0}", Request.Form['sex']);