简体   繁体   中英

Javascript: Radio button group validation

We have a webform and here is how the radio code is set up in this php form:

<input type="radio" name="2074" id="2074" value="Yes" class="valuetext" >Yes
<input type="radio" name="2074" id="2074" value="No" class="valuetext" >No

I'm working on some custom validation code that is fine for the text fields, but just hit a snag with radio buttons, so I'm sure this will be an issues for check-boxes

so here is the code that validates,

function blank(field) {
    if ((field.type == "text" || field.type == "textarea") && (field.value == " " || field.value == ""))
    {
        return true;
    }
    else if ((field.type ="radio" || field.type == "checkbox") && (!(field.checked || field.selected || field.selectedIndex > -1)))
    {
        return true;
    }
    else {
        return false;
    }
}

but when it comes to the radio buttons, it only checks the first radio button it runs into. so for example, if I run the validation and neither radio in the set is checked, it works, gives me the error message i needed, but that is only because it checked the first button, which was empty.

if I select " no ", the second option of the radio, it does not work correctly, show me an error message when it should not

if I select " Yes " the first option of the radio, it works as expected.

How do I get JavaScript to grab all the radios in the group, check if any in that group are checked ?

Thank you in advance.

Function that gathers fields that need to be examined: * Also, that is a json script above this that provides the data for fieldlist *

var field = [], blankFields = [],
        listText = [], listItem = [], fieldId = [], label = [];

function checkRequired(fieldList) {
    for (var i = 0; i < fieldList.length; i++)
    {
        listText = fieldList[i];
        listText = listText.substring(1, listText.length - 1);
        listItem = listText.split("||");
        fieldId = listItem[0];
        label = listItem[1];
        field = document.getElementById(fieldId);

        if (visible(field) && blank(field)){
            blankFields.push(label);
        }
    }
    //return blankFields;
    if (blankFields.length > 0) {
        displayError(blankFields);
    }
}

You can use document.getElementsByName("2074") and then iterate through to see if any are checked.

Related question: In JavaScript, how can I get all radio buttons in the page with a given name?

I decided to mix in some jquery which made life tons easier:

else if (field.type=="radio")
                {
                 var radiocheck = $('input[type="radio"][name="' + field.name + '"]:checked').size() > 0;
                 if (radiocheck == false){
                     return true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM