4

I've got 2 radio buttons within a form here,

<form action='' method='post' onsubmit='return checkForm(this, event)'>
     <input type = 'radio' name='allow' value='allow' checked>Allow
     <input type='radio' name='allow' value='disallow'>Disallow
</form>

And in the checkForm function, there is a piece of code to verify whether the user checks the Disallow button, if yes, show an alert to force the user to allow, if not, return true.

Yet, I found that when I first checked the Disallow button, and the sign showed, and then I change it to Allow, but there is still the alert sign popping saying that I should alter my choice to Allow

This is the checkForm function:

<script type="text/javascript">
    function checkForm(form, event) {
        var radio  = document.getElementsByName("allow");
        var counter=0;
        for(i=0;i<radio.length;i++){
            if(radio[i].value=="disallow"){
                alert("Please allow the system to get your data!");
                return false;
            }
        }
        return true;    
    }
</script>

Any ideas? Thanks a lot.

Pooya Raki
  • 219
  • 1
  • 3
  • 17
Lykas
  • 117
  • 10
  • 1
    The attribute you want to test is checked, not value. https://stackoverflow.com/questions/21166860/check-a-radio-button-with-javascript – Dave Pile Aug 04 '18 at 04:22

2 Answers2

0

You need to check if the option is checked or not:

<script type="text/javascript">
function checkForm(form, event) {
    var radio  = document.getElementsByName("allow");
    var counter=0;
    for(i=0;i<radio.length;i++){
        if(radio[i].checked && radio[i].value=="disallow") {
            alert("Please allow the system to get your data!");
            return false;
        }
    }
    return true;    
}
</script>

Modern browsers:

function checkForm(form, event) {
    if(document.querySelector('input[name="allow"]:checked').value=="disallow") {
        alert("Please allow the system to get your data!");
        return false;
    }

    return true;    
}
Pooya Raki
  • 219
  • 1
  • 3
  • 17
0

I think I found some things wrong with your HTML code:

<input type='radio' name='allow' value='disallow' Disallow

This tag is not closed, it should be

<input type='radio' name='allow' value='disallow'> Disallow

Also, what version of HTML are you using? If you're using HTML5 or XHTML Strict, then you need to self-close:

<input type='radio' name='allow' value='disallow' /> Disallow
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79