user4107395
user4107395

Reputation: 141

JavaScript Form Validation -

I'm trying to get a basic javascript validation. For some reason it's picking up text and drop downs but not radio buttons? What am I doing wrong?

JS Fiddle

<script>
    function validateForm(formId)
    {
        var inputs, index;
        var form=document.getElementById(formId);
        inputs = form.getElementsByTagName('input');
        for (index = 0; index < inputs.length; ++index) {
            // deal with inputs[index] element.
            if (inputs[index].value==null || inputs[index].value==""))
                {
                    alert("Field is empty");
                    return false;
                 }
     }
</script> 

Upvotes: 2

Views: 115

Answers (2)

jozzy
jozzy

Reputation: 2943

Provided below is an approach you can take to identify if you have multiple radio buttons in your form

function hasEmptyRadio(radioMap) {
    var emptyRadio = false;
    for (var i in radioMap) {
        if (radioMap.hasOwnProperty(i) && !radioMap[i]) {
            emptyRadio = true;
            break;
        }
    }
    return emptyRadio; // return the radio object or name if required
}

function markEmptyRadios(radioMap, radioObj) {
    var checked = radioObj.checked;
    radioMap[radioObj.name] = radioMap[radioObj.name] || checked;
}


function validateForm(formId) {
    var inputs, index;
    var radioMap = {};
    var form = document.getElementById(formId);
    inputs = form.getElementsByTagName('input');
    for (index = 0; index < inputs.length; ++index) {
        if (inputs[index].type === 'radio') {
            markEmptyRadios(radioMap, inputs[index])
        }
        // Your check for other input type can go here
    }
    alert("Radio Empty check returned => " + hasEmptyRadio(radioMap));
}

Upvotes: 1

DirtyBit
DirtyBit

Reputation: 16772

To validate for radio buttons, You need to go through all radio's and see which one's checked property is true.

<script>
      function validateForm(){
            for(i=0; i<document.form.radios.length; i++){       
              if(document.form.radios[i].checked==false){
              c=1;
              }
                else{
                c=0;
                break;
                }}        

                if(c==1){
                alert('Please select an option');
                }
         }
 </script>

document.form.radios.length gives the number of radio buttons.

You can also use HTML's required attribute to achieve the same functionality.

<form>
      <input type="radio" name="gender" value="Male" required /> Male
      <input type="radio" name="gender" value="Female" /> Female

      <input type="submit" name = "sub" value="SAVE" />
</form>

Fiddle

Upvotes: 1

Related Questions