Sajeed Thajudeen Sajeed Thajudeen - 17 days ago 7
HTML Question

Radio Button Value display on another form

I am facing issue to transfer checked radio button value from one form to another

My code in below

<html>

<body>
<form id-"from1">
<input name="gender[]" id="gender[]" type="radio" value="male" checked>
<input name="gender[]" id="gender[]" type="radio" value="female" >

<input type="button" border="2" onClick="checkedRadio();" >
</form>

<form id="form2">

<p id="view" id="view">Display Here</p>

</form>
<script>

function checkedRadio() {

var input = document.getElementById("gender[]").value;
document.getElementById("view").innerHTML = input;


}
</script>
</body>
</html>`


`
and I'm getting results as "male" always. please any one can help me on this issue, and it is preferred to get result as instead of

Answer

You are trying to get the value of all radios. You need to use querySelector and query it by name, but not id. Here's your fixed code

<html>

<body>
<form id="form1">
<input name="gender" id="genderMale" type="radio" value="male" checked>
<input name="gender" id="genderFemale" type="radio" value="female">

<input type="button" border="2" onClick="checkedRadio();" >
</form>

<form id="form2">

<p id="view" id="view">Display Here</p>

</form>
<script>

    function checkedRadio() {
        var input = document.querySelector('input[name="gender"]:checked').value;
        document.getElementById("view").innerHTML = input;
    }
</script>
</body>
</html>
Comments