Skip to content Skip to sidebar Skip to footer

Using Javascript To Check If A Radio Button Is Selected And Return A Specific Answer Based On The Selection

I am looking, in the cleanest way possible to be able to take a simple yes or no question and test for which answer has been chosen. For instance in this case if a 'yes' I want it

Solution 1:

A few things:

document.getElementByID() 

will always return the first element, as ID's are supposed to be unique. Instead, use:

document.getElementsByName('substance');

Next, in your loop, you are improperly referencing the array's members using the .length property. Try this instead:

    for (i = 0; i < substanceab.length; i++)
    {
        if(substanceab[i].checked)
        {
            user_input = substanceab[i].value;
        }
    }

Finally, in javascript, the '=' opertator is always an assignment statement. To do comparisons, always use '==':

if (user_input == "yes")
    {
        return answer = "Continue";
    }
    elseif (user_input =="no")
    {
        return answer = "Provide Alternate Referral";
    }
    else
    {
        return;
    }  

Also, try to avoid global variables whenever possible. Here is the working code, refactored a bit:

<input type="radio" value="no" id= "Sub" name="substance" onclick="writeAns()">

functioncheckForm() 
{
    var user_input;

    var substanceab = document.getElementsByName('substance');
    for (i = 0; i < substanceab.length; i++)
    {
        if(substanceab[i].checked)
        {
            user_input = substanceab[i].value;
        }
    }

    if (user_input == "yes")
    {
        return"Continue";
    }
    elseif (user_input =="no")
    {
        return"Provide Alternate Referral";
    }
    else
    {
        return;
    }   
};
functionwriteAns()
{
    document.getElementById('answerwrite').innerHTML = checkForm();
};

Solution 2:

Very easy if you are using JQuery.

Ensure your elements have the same "name" attribute and use:

varRadioGroupResult = $('input[name="MyRadioGroupNameHere"]:checked').val();

Nice and simple.

Post a Comment for "Using Javascript To Check If A Radio Button Is Selected And Return A Specific Answer Based On The Selection"